The first program

A Scala file is a compilation unit, not a script: a statement cannot stand at the top level of a .scala file. A program starts at an entry point, and @main declares one: the compiler writes the main method that the JVM looks for, and the method's parameters become the arguments of the program.

The program

hello.scala

@main def hello(): Unit = println("Hello, Scala")

scala-cli run --server=false hello.scala

Hello, Scala

println writes a line, takes any value and returns Unit, the Scala type with one value, written (). The declared result type is not required — the compiler infers it — but a program's entry point states it, because a reader should not have to infer what a program returns.

The body is an indented block: the two spaces after = are syntax, not decoration. A file that mixes tabs and spaces in one block does not compile, and the course uses two spaces, which is what scalafmt writes.

Arguments of a program

The parameters of an @main method are the command line arguments, with the type of each one parsed by the launcher. One string is enough for the greeting, and the words after -- are what scala-cli passes to the program:

greet.scala

@main def greet(name: String): Unit = println(s"Hello, $name")

scala-cli run --server=false greet.scala -- Ada

Hello, Ada

An Int parameter would be parsed as a number, and a missing argument stops the program with a usage message before the body runs. A program that needs optional words rather than a fixed list takes Array[String] as its single parameter, or reads args in a script.

Values and expressions

The body of the method is a sequence of expressions, and the last one is the result. The arithmetic below uses integer division, a remainder and a floating-point division on the same number, which is the first difference a Java programmer meets:

arithmetic.scala

@main def arithmetic(): Unit = val seconds = 90 val minutes = seconds / 60 val rest = seconds % 60 println(s"$minutes min $rest s") println(seconds.toDouble / 60)

scala-cli run --server=false arithmetic.scala

1 min 30 s
1.5

seconds / 60 is integer division, so it gives 1 and the remainder carries the other thirty seconds. toDouble converts before the division, and then the result is a Double. The s"..." prefix is an interpolator: $minutes is the value, not the name. The strings lesson covers all three interpolators.

Related

Автор статьи: Arthur Isaev