App 2: Handling Quit

The first thing to do in handleUserInput is to handle the “quit” case. Basically all we have to do is call System.exit(0) when we see that the user has typed the letter "q". However, because handleUserInput returns Try[Unit], we need to wrap that call in a Try, like this:

def handleUserInput(input: String): Try[Unit] = input match
    case "q" => 
        Try(System.exit(0))     // <== THE NEW CODE
    // more cases here ...

Because System.exit returns Unit, this works as desired.

A Scala REPL tip

Note that you can use the Scala REPL’s :type command to verify that System.exit returns Unit:

scala> :type System.exit(0)

So that’s all we have to do for the “Quit” use case.