Reading Input and Arguments
Prerequisites: Option: no more null
Command-line arguments
An @main method's parameters become command-line arguments —
Scala parses and checks them for you:
// illustrative
@main def greet(name: String, times: Int): Unit =
for _ <- 1 to times do println(s"Hello, $name!")
$ scala run greet.scala -- Ada 2
Hello, Ada!
Hello, Ada!
$ scala run greet.scala -- Ada two
Illegal command line after first argument: java.lang.NumberFormatException: For input string: "two"
The arguments after -- go to your program. For a variable number of
arguments, use @main def run(args: String*). The built-in message for
invalid input is terse, so real tools often use a library such as
mainargs or decline, or parse args themselves.
Reading from the keyboard
// illustrative
import scala.io.StdIn
@main def ask(): Unit =
val name = StdIn.readLine("What is your name? ")
val age = StdIn.readLine("How old are you? ").toIntOption
age match
case Some(a) => println(s"Hi $name, next year you'll be ${a + 1}.")
case None => println(s"Hi $name, that wasn't a number.")
What is your name? Ada
How old are you? 36
Hi Ada, next year you'll be 37.
readLine always returns a String, so convert it with toIntOption (or
toDoubleOption) and handle invalid input.
Reading all input lines
// illustrative
import scala.io.Source
@main def sumLines(): Unit =
val numbers = Source.stdin.getLines().flatMap(_.toIntOption).toList
println(s"Sum: ${numbers.sum}")
Run it with piped input — printf "1\n2\nx\n3\n" | scala run sum.scala —
and it prints Sum: 6, skipping the invalid line.