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;
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With