Reputation: 151
I have an API which converts an Option[Int] to a String. I want to convert this back to an Option[Int]. What's the best way of doing this in Scala?
val x = Some(1)
val y = x.toString
val z: Option[Int] = ??? // Expected value is Some(1) from y
Upvotes: 0
Views: 529
Reputation: 48400
In Scala 2.13
y match {
case s"Some($x)" => x.toIntOption
case _ => None
}
In Scala 2.12
val someInt = """Some\((\d+)\)""".r
y match {
case someInt(x) => Try(x.toInt).toOption
case _ => None
}
Upvotes: 2