Reputation: 3248
The java library I am dealing with, returns null
on errors. Is there an Idiomatic way of saying:
val x:Option[T]
if(x.isEmpty)
false
else
x.get.isFooable()
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()
Upvotes: 2
Views: 4632
Reputation: 2769
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 }
Upvotes: 5
Reputation: 3696
x.exists(_.isFooable) // Returns false if x is None
If you want true
as the default for None
, use x.forall
Upvotes: 10