Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala equivalent of `??` operator in C# [duplicate]

Tags:

c#

scala

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;
like image 491
user3621445 Avatar asked Oct 06 '10 15:10

user3621445


1 Answers

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.)

like image 186
Rex Kerr Avatar answered Sep 30 '22 18:09

Rex Kerr