13

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?

Eduardo
  • 8,362
  • 6
  • 38
  • 72

2 Answers2

22

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

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • 2
    Thanks! I have also found `for(x <- ob if x) yield x` – Eduardo Jun 18 '13 at 22:39
  • 2
    @Eduardo - Indeed. There's also `ob.filterNot(! _)`, `ob.find(identity)`, `ob.collect{ case true => true }`, and various others. You can also write `x=>x` in place of `identity`. – Rex Kerr Jun 18 '13 at 22:58
6

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 }
Marcel Molina
  • 994
  • 6
  • 6
  • 4
    Instead of `exists { _ == true }` it is more sensible to write `exists(identity)` or `contains(true)`. Comparing bool to true is frowned upon by many programmers [Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java](http://stackoverflow.com/questions/2661110/is-it-bad-to-explicitly-compare-against-boolean-constants-e-g-if-b-false-i). – Suma Apr 06 '15 at 15:27