Eduardo
Eduardo

Reputation: 8392

Idiomatic way of treating Option[Boolean]

In my Scala program, I am receiving some JSON.

One of the fields is an optional Boolean. If the field is missing, or if its value is false, I would like to return None. If its value is true, I would like to return Some(true).

SInce this is equivalent to converting Some(false) into None, I have defined the following function:

def boolmap(ob: Option[Boolean]) = if(ob == Some(false)) None else ob

It works, but it doesn't seem to be very idiomatic. Is there anything more elegant?

Upvotes: 13

Views: 18466

Answers (2)

Marcel Molina
Marcel Molina

Reputation: 1004

I agree with others that you might as well just return true or false since you aren't differentiating between the attribute not being there at all, being null or being false.

If you just returned Boolean you could do it this way:

scala> Some(true) exists { _ == true }
res0: true

scala> Some(false) exists { _ == true }
res1: Boolean = false

scala> None exists { _ == true }
res2: Boolean = false

If you insist on returning Option[Boolean] a pattern match would be more idiomatic:

ob match { 
  case Some(true) => Some(true) 
  case _          => None 
}

You could also use collect but in this case it would look IMO weird:

obj collect { case true => true }

Upvotes: 7

Rex Kerr
Rex Kerr

Reputation: 167891

This is ob.filter(identity). I'm not sure whether that's clearer, but it's shorter.

Upvotes: 22

Related Questions