Your First Program
Prerequisites: Installing Scala
Create a file named hello.scala:
@main def hello(): Unit =
println("Hello, world!")
println("Welcome to Scala.")
Run it:
scala run hello.scala
Expected output
Hello, world!
Welcome to Scala.
Line by line:
@mainmarks the method where the program starts.def hello()defines a method calledhellowith no parameters.: Unitis the return type —Unitmeans "returns nothing useful", likevoidin Java.=introduces the method's body.- The indented lines below are the body. Scala 3 uses indentation to group code, like Python.
printlnprints a line of text.
Braces are optional
Scala 3 also accepts curly braces, the only style in Scala 2 — you'll see both in real code:
@main def hello(): Unit = {
println("Hello, world!")
}
Hello, world!
This course uses the indentation style of the official Scala 3 documentation.
Common mistakes
- Inconsistent indentation: lines in the same block must line up.
- Forgetting the
=after the method signature. In Scala 3 that's a syntax error.
Practice
Write a program that prints your name on one line and your favorite food on the next.
Show solution
@main def aboutMe(): Unit =
println("Ada")
println("Pizza")
Ada
Pizza