home search about rss feed twitter ko-fi

App 2: Read User Input (Scala 3 Video)

To read input from a user, we use the readLine function that’s in the scala.io.StdIn data type. Again — imagining that we’re reading input in a REST service — we know that we want to return a Try:

def readInput(): Try

Because readLine returns a String, the function returns a Try[String], and the complete function looks like this:

def readInput(): Try[String] = Try {
    StdIn.readLine()
}

Now I add this function to the IOHelper object:

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

object IOHelper:

    def promptUser(): Try[Unit] = Try {
        println("\n(Commands: a \"task\", d 1, u 1, h, q, v)")
        print("Yo: ")
    }

    def readInput(): Try[String] = Try {
        StdIn.readLine()
    }

end IOHelper

At this point, if all I was going to do was prompt the user one time and then read their input, I could add readInput to my main method, like this:

import IOHelper.*

@main def ToDoList() = 
    val db = Database("./ToDoList.dat")
    promptUser()
    val input: Try[String] = readInput()

After that I would handle the input value, most likely in a match expression.

However, this is not what I want. What I really want is to keep prompting the user inside some sort of loop. But first, let’s write one more I/O function while we’re in this neighborhood.

Update: All of my new videos are now on
LearnScala.dev