Idiomatically evaluate to true if the parameter contains a specific value

I want to write a method that returns true

if it Option[Int]

contains a certain value and false otherwise. What's the idiomatic way to do 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 refer to this approach as less-diomatic .

Is there a way to do the same using map

, filter

or something else?

I got this far, but this only changes the problem to "Return true if Option contains true

", which is actually the same as "Return true if Option contains 5


var trueIf5(intOption: Option[Int]): Boolean { => i == 5).???



source to share

3 answers

Since you are checking if 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.
res0: Boolean = false


These inline warnings are not as effective with universal equality:

scala> Option(42).exists("" == _)    // no warning
res1: Boolean = false




intOption.exists(_ == 5)





Why didn't anyone suggest:

intOption == Some(5)




All Articles