开发者

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

This question already has answers here: 开发者_如何学运维 Closed 12 years ago.

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


Try getOrElse. My friend suggested.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜