How to check for null or false in Scala concisely?

2019-02-01 05:30发布

In Groovy language, it is very simple to check for null or false like:

groovy code:

def some = getSomething()
if(some) {
// do something with some as it is not null or emtpy 

}

In Groovy if some is null or is empty string or is zero number etc. will evaluate to false. What is similar concise method of testing for null or false in Scala? What is the simple answer to this part of the question assuming some is simply of Java type String?

Also another even better method in groovy is:

def str = some?.toString()

which means if some is not null then the toString method on some would be invoked instead of throwing NPE in case some was null. What is similar in Scala?

标签: scala null
7条回答
Luminary・发光体
2楼-- · 2019-02-01 06:30

What you ask for is something in the line of Safe Navigation Operator (?.) of Groovy, andand gem of Ruby, or accessor variant of the existential operator (?.) of CoffeeScript. For such cases, I generally use ? method of my RichOption[T], which is defined as follows

class RichOption[T](option: Option[T]) {
  def ?[V](f: T => Option[V]): Option[V] = option match {
    case Some(v) => f(v)
    case _ => None
  }
}

implicit def option2RichOption[T](option: Option[T]): RichOption[T] =
  new RichOption[T](option)

and used as follows

scala> val xs = None
xs: None.type = None

scala> xs.?(_ => Option("gotcha"))
res1: Option[java.lang.String] = None

scala> val ys = Some(1)
ys: Some[Int] = Some(1)

scala> ys.?(x => Some(x * 2))
res2: Option[Int] = Some(2)
查看更多
登录 后发表回答