14.12. Prompting for Input from a Scala Shell Script

Problem

You want to prompt a user for input from a Scala shell script and read her responses.

Solution

Use the readLine, print, printf, and Console.read* methods to read user input, as demonstrated in the following script. Comments in the script describe each method:

#!/bin/sh
exec scala "$0" "$@"
!#

// write some text out to the user with Console.println
Console.println("Hello")

// Console is imported by default, so it's not really needed, just use println
println("World")

// readLine lets you prompt the user and read their input as a String
val name = readLine("What's your name? ")

// readInt lets you read an Int, but you have to prompt the user manually
print("How old are you? ")
val age = readInt()

// you can also print output with printf
println(s"Your name is $name and you are $age years old.")

Discussion

The readLine method lets you prompt a user for input, but the other read* methods don’t, so you need to prompt the user manually with print, println, or printf.

You can list the Console.read* methods in the Scala REPL:

scala> Console.read
readBoolean   readByte   readChar   readDouble   readFloat
readInt       readLine   readLong   readShort    readf
readf1        readf2     readf3

Be careful with the methods that read numeric values; as you might expect, they can all throw a NumberFormatException.

Although these methods are thorough, if you prefer, you can also fall back and read input with the Java Scanner class:

// you can also use the Java Scanner class, if ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.