8

Possible Duplicate:
How to write a proper null-safe coalescing operator in scala?

What is the Scala equivalent of ?? operator in C#?

example:

string result = value1 ?? value2 ?? value3 ?? String.Empty;
Community
  • 1
  • 1
user3621445
  • 81
  • 1
  • 2
  • http://stackoverflow.com/questions/1364361/how-to-write-a-proper-null-safe-coalescing-operator-in-scala ? – Philippe Oct 06 '10 at 15:17

5 Answers5

10

You can write your own with identical semantics--here's one that insists on the same type throughout due to left-to-right evaluation, but one could change it to ?: to get right-to-left evaluation that would widen types as needed:

class CoalesceNull[A <: AnyRef](a: A) { def ??(b: A) = if (a==null) b else a }
implicit def coalesce_anything[A <: AnyRef](a: A) = new CoalesceNull(a)

scala> (null:String) ?? (null:String) ?? "(default value)"
res0: String = (default value)

But the reason why this operator doesn't exist may be that Option is the preferred way of dealing with such scenarios as well as many similar cases of handling of non-existent values:

scala> List((null:String),(null:String),"(default value)").flatMap(Option(_)).headOption
res72: Option[java.lang.String] = Some((default value))

(If you were sure that at least one was non-null, you could just use head; note that this works because Option(null) converts to None and flatMap gathers together only the Some(_) entries.)

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • 2
    I believe it should be `def ??(b: => A)` to make the semantics identical. I think the right side of the elvis operator should not be evaluated unless `a` is `null`. May be wrong though. – sinharaj Feb 13 '13 at 00:27
  • @sinharaj - You're probably right. I'm not that familiar with how C# does this. – Rex Kerr Feb 13 '13 at 11:41
5

Try getOrElse. My friend suggested.

Andriy Buday
  • 1,959
  • 1
  • 17
  • 40
  • 2
    Not a proper operator but could be handy for simple expressions: `Option(null:String).getOrElse("default value")` or `Option(Option(null:String).getOrElse(null:String)).getOrElse("default value")` – karmakaze Jan 31 '14 at 17:01
2

I dont believe there is one. You can see this post for an implementation of the null coalescing operator.

Community
  • 1
  • 1
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
2

See linked answer, but, more to the point, avoids nulls. Use Option.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
1

This blog post covers how to implement Groovy's "Elvis operator ?:" in Scala. This does the same thing as C#'s ?? operator.