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).???
}
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
intOption.exists(_ == 5)
The doc
Why has no one suggested:
intOption == Some(5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With