A better way to test the value of an Option?
How about if (opt == Some(“lakes”)) This expresses the intent clearly and is straight forward.
How about if (opt == Some(“lakes”)) This expresses the intent clearly and is straight forward.
Maybe something like this: somethingReturningAnOpt match { case Some(actualThingIWant) => doSomethingWith(actualThingIWant) case None => } or as pst suggests: somethingReturningAnOpt.foreach { actualThingIWant => doSomethingWith(actualThingIWant) } // or… for (actualThingIWant <- somethingReturningAnOpt) { doSomethingWith(actualThingIWant) }
No, if you do it this way, you can’t leave out the type. The type of Left(“No number”) is inferred to be Either[String, Nothing]. From just Left(“No number”) the compiler can’t know that you want the second type of the Either to be Int, and type inference doesn’t go so far that the compiler will … Read more
What you should do is check using exists. Like so: myOption.exists(_.trim.nonEmpty) which will return True if and only if the Option[String] is not None and not empty.
I personally find methods like cata that take two closures as arguments are often overdoing it. Do you really gain in readability over map + getOrElse? Think of a newcomer to your code: What will they make of opt cata { x => x + 1, 0 } Do you really think this is clearer … Read more
You would lose some type safety and possibly cause confusion. For example: val iThinkThisIsAList = 2 for (i <- iThinkThisIsAList) yield { i + 1 } I (for whatever reason) thought I had a list, and it didn’t get caught by the compiler when I iterated over it because it was auto-converted to an Option[Int]. … Read more
In Scala 2.8, flatten will work: Welcome to Scala version 2.8.0.RC2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_20). Type in expressions to have them evaluated. Type :help for more information. scala> val listOfOptions = List(None, Some(“hi”), None) listOfOptions: List[Option[java.lang.String]] = List(None, Some(hi), None) scala> listOfOptions flatten res0: List[java.lang.String] = List(hi) This doesn’t work in 2.7.7, … Read more
It’s a shame that flatten doesn’t exist. It should. Flatten does exist now. As before, s getOrElse None (in addition to the other answers) will also do the same thing.
scala> import scala.util.Try import scala.util.Try scala> def tryToInt( s: String ) = Try(s.toInt).toOption tryToInt: (s: String)Option[Int] scala> tryToInt(“123”) res0: Option[Int] = Some(123) scala> tryToInt(“”) res1: Option[Int] = None
You should use Option(null) to reach the desired effect and return None. Some(null) just creates a new Option with a defined value (hence Some) which is actually null, and there are few valid reasons to ever create one like this in real code.