Suppose we have an Option[String], and if there is Some(string) in there, we want to turn it into an Int to .toInt. I would do the following:
val foo: Option[String] = Some("5")
val baz: Option[Int] = foo match {
case Some(thing) => Some(thing.toInt)
case None => None
}
This works great. However, it seems extremely verbose and like a lot of work. Can anyone show me a simpler way of doing this?
Thanks!
Seems that you need to map
:
val baz = foo map (_ toInt)
Option
type support many collection operations (like map
, filter
, etc.) and a lot of nice helpful functions. Just take a look at scaladoc:
http://www.scala-lang.org/api/rc/scala/Option.html
Also this cheat sheet can be helpful:
http://blog.tmorris.net/scalaoption-cheat-sheet/
All you need is foo.map(_.toInt)
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