Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Option[T] to Option[U] in Scala

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!

like image 662
Jay Taylor Avatar asked Nov 10 '11 22:11

Jay Taylor


2 Answers

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/

like image 155
tenshi Avatar answered Nov 19 '22 17:11

tenshi


All you need is foo.map(_.toInt)

like image 41
Ben Jackson Avatar answered Nov 19 '22 16:11

Ben Jackson