Nicholas Marshall
Nicholas Marshall

Reputation: 3248

Idiomatic way of If none return false?

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

Answers (4)

Yuriy
Yuriy

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

Kristian Domagala
Kristian Domagala

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

Faiz
Faiz

Reputation: 16265

You want

x map (_.isFooAble()).getOrElse(false)

Upvotes: 1

Ankur
Ankur

Reputation: 33657

x map (_.isFooable) getOrElse false

Upvotes: 3

Related Questions