Using the Option way
Let's try and change the function signature in a way that we can reason about and modify it so that it does what it says:
def toInt(str: String): Option[Int] = Try(str.toInt) match { case Success(value) => Some(value) case Failure(_) => None }
In the preceding definition, we knew that the response was optional. We might or might not get a corresponding integer value for every string we pass to our function. Hence, we made the response type an Option[Int]
. Also, as you may have noticed, we used another construct available to us from the scala.util
package, named Try
. How do we use Try
? We pass a function for its evaluation to the Try
block's constructor/apply method. As might be obvious, the Try
block's apply
method takes a function as a by-name
parameter, which tries to evaluate that function. Based on the result or exception, it responds as a Success(value)
or Failure(exception)
.
We used the Try
construct and passed logic as an argument. On success, we responded...