FEH: allCatch

Before we leave these error-handling lessons and get back to the change request for our wc application, I want to show how you can write those makeInt functions more concisely.

More concise makeInt functions

You can make most of the makeInt functions I showed previously more concise by using a Scala type named allCatch. Cutting to the chase, its solutions to make makeInt much shorter look like this:

import scala.util.{Try, Success, Failure}

// the allCatch type is here:
import scala.util.control.Exception.allCatch

// Option
def makeInt(s: String): Option[Int] =
    allCatch.opt(s.toInt)

// Either
def makeInt(s: String): Either[Throwable, Int] = 
    allCatch.either(s.toInt)

// Try (Version 1: the approach shown earlier (preferred))
def makeInt(s: String): Try[Int] =
    Try(s.toInt)

// Try (Version 2)
def makeInt(s: String): Try[Int] = 
    allCatch.withTry(s.toInt)

As shown in the second import statement, allCatch is defined in the Exception object of the scala.util.control package, so you need to first import it, and then you can use it as shown.

The key with allCatch is that it does the work that the try/catch expression did in my previous examples: it returns the success value when the conversion succeeds (the happy path), and it catches exceptions when things go wrong and returns the desired error value (in the unhappy path).

More information

The scala.util.control.Exception Scaladoc page has more information and examples of allCatch and other related solutions, such as how to handle logging when using shortcuts like this. Please see that page for more information on those techniques.