Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatically evaluate true if Option contains specific value

Tags:

scala

I want to write a method that returns true if an Option[Int] contains a specific value and false otherwise. What is the idiomatic way of doing this?

var trueIf5(intOption: Option[Int]): Boolean {
  intOption match {
    case Some(i) => i == 5
    case None => false
  }
}

This above solution clearly works, but the Scala docs label this approach as less-idiomatic.

Is there some way I can do the same thing using map, filter, or something else?

I got this far, but it only changes the problem to "Return true if Option contains true", which is effectively the same as "Return true if Option contains 5".

var trueIf5(intOption: Option[Int]): Boolean {
  intOption.map(i => i == 5).???
}
like image 563
Cory Klein Avatar asked Oct 02 '14 16:10

Cory Klein


3 Answers

Since you're testing whether it contains a value:

scala> Some(42) contains 42
res0: Boolean = true

Don't neglect your -Xlint:

scala> Option(42).contains("")
res0: Boolean = false

scala> :replay -Xlint
Replaying: Option(42).contains("")
<console>:12: warning: a type was inferred to be `Any`; this may indicate a programming error.
       Option(42).contains("")
                           ^
res0: Boolean = false

Those built-in warnings aren't as effective with universal equality:

scala> Option(42).exists("" == _)    // no warning
res1: Boolean = false
like image 175
som-snytt Avatar answered Nov 07 '22 07:11

som-snytt


intOption.exists(_ == 5)

The doc

like image 12
sjrd Avatar answered Nov 07 '22 05:11

sjrd


Why has no one suggested:

intOption == Some(5)
like image 3
Chris Martin Avatar answered Nov 07 '22 07:11

Chris Martin