Learn Scala Programming
上QQ阅读APP看书,第一时间看更新

Optional parsing for string literals

In Scala 2.13, StringOps has been extended with methods that return Option for string-literals parsing. Supported types include all numeric types and Boolean.

The new methods can greatly simplify the processing of user-provided data without the need to wrap the calls with the exception-handling, as shown in the following example:

scala> "10".toIntOption
res3: Option[Int] = Some(10)
scala> "TrUe".toBooleanOption
res4: Option[Boolean] = Some(true)
scala> val bool = "Not True"
bool: String = Not True
scala> bool.toBooleanOption
res5: Option[Boolean] = None

The optional Boolean parsing ignores the case of the argument the same way the exception-throwing toBoolean method does.