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;
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;
I dont believe there is one. You can see this post for an implementation of the null coalescing operator.
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.)
See linked answer, but, more to the point, avoids nulls. Use Option.
This blog post covers how to implement Groovy's "Elvis operator ?:
" in Scala. This does the same thing as C#'s ??
operator.