home search about rss feed twitter ko-fi

App 2: Show Help Text (Scala 3 Video)

The other function I want to write while we’re in this neighborhood is a “help” function. It’s similar to promptUser in that it just prints to STDOUT, so I follow that same recipe:

  • It’s a function that returns Try[Unit]
  • I create the function using Try’s constructor (putting the println inside Try{...}.)

Here’s the new showHelp function, inside 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()
    }

    def showHelp(): Try[Unit] = Try {
        val text = """
        |  Possible commands
        |  -----------------
        |  a <task>         - add a to-do item
        |  h                - show this help text
        |  d [task number]  - delete a task by its number
        |  v                - view the list of tasks
        |  q                - quit
        """.stripMargin.trim
        println(text)
    }

end IOHelper

Multiline strings

What’s new in this function is that it uses a multiline String. You create a multiline string in Scala using triple-quotes, as shown. The use of triple-quotes, the | character at the beginning of each line, and then the stripMargin and trim method calls on the string turns a string like this:

val s = """
    |Alvin Alexander
    |123 Main Street
    |Talkeetna, AK 9967
""".stripMargin.trim

into a left-aligned string that prints like this:

Alvin Alexander
123 Main Street
Talkeetna, AK 9967

For more information on multiline strings, see my blog post, How to create multiline strings in Scala

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