Nicholas Marshall Nicholas Marshall - 7 months ago 122
Scala Question

Idiomatic way of If none return false?

The java library I am dealing with, returns

on errors. Is there an Idiomatic way of saying:

val x:Option[T]


I have looked at the answers at Scala: Boolean to Option. Those are close to what I want, there is more idiomatic way then:

x.isDefined && x.get.isFooable()

Answer Source

The are many ways to process Option. Most idiomatic is lift computation to Option:

val x = Option(true)
x map { if(_) 10 else 20 }

If you use Option[Boolean] for conditional branching than pattern matching is most preferable:

c match {
  case Some(true)  => println("True")
  case Some(false) => println("False")
  case None        => println("Undefined")

And your case:

x.isDefined && x.get.isFooable()

little bit clearly:

x map { _.isFooable } getOrElse false

and finally with Scala Option utility method:

x exists { _.isFooable }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download