Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 37 ยท Getting Started

Your First Scala Program

Write your first Scala 3 program: the @main annotation, println, command-line arguments, top-level definitions, and what the older object-with-main style looks like.

Every language starts with "Hello, World", and Scala's version is very short. In this lesson you will write it, take it apart, read command-line arguments, and learn how the older Scala 2 and Java-style entry points compare. The code is read-only here, but each idea has a runnable Java or Kotlin counterpart so you can see the behaviour.

Hello, World

SCALA
@main def hello(): Unit =
  println("Hello, World!")

Save it as hello.scala and run scala-cli run hello.scala. It prints:

TEXT
Hello, World!

Four things happen in those two lines:

  • @main marks a method as the program's entry point. Scala generates the JVM main method for you.
  • def declares a method named hello.
  • (): Unit says it takes no parameters and returns Unit, Scala's "no useful result" type (like void).
  • The body is indented under =. There are no braces and no semicolons.

println writes a line to standard output. It is available everywhere without an import because it is part of the Predef object that Scala imports automatically.

Here is the same shape in Kotlin, which you can run. Notice how close the two feel:

Kotlin Hello in Kotlin (comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Top-level definitions

In Scala 3 you can place methods, values and classes directly in a file. You do not need a wrapper class or object:

SCALA
val greeting = "Hello"

def shout(text: String): String =
  text.toUpperCase + "!"

@main def run(): Unit =
  println(shout(greeting))

Output: HELLO!

Behind the scenes the compiler wraps top-level definitions in a synthetic object named after the file, but you rarely need to think about it. Compare with Java, where everything lives in a class.

Reading command-line arguments

A @main method can take parameters. Scala converts the command-line strings for you:

SCALA
@main def add(a: Int, b: Int): Unit =
  println(a + b)
Terminal
scala-cli run add.scala -- 3 4
TEXT
7

Arguments after -- go to your program. If a value cannot be converted (for example abc for an Int), the generated code prints a usage error instead of crashing with an exception. For a variable number of arguments use a repeated parameter:

SCALA
@main def total(numbers: Int*): Unit =
  println(numbers.sum)

total 1 2 3 4 prints 10. If you prefer raw strings, take args: String* and parse yourself.

The runnable Java stand-in reads arguments the traditional way. Our runner passes none, so we simulate a few:

Java Arguments in Java (simulated)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Printing

You will use these constantly:

SCALA
println("with newline")   // prints and ends the line
print("no newline")       // prints without ending the line
println(42)               // any value can be printed
println(List(1, 2, 3))    // List(1, 2, 3)

println calls toString on the value. Formatting with variables is the job of string interpolation, which we cover soon:

SCALA
val name = "Ada"
println(s"Hi, $name")   // Hi, Ada

Other entry-point styles

You will see two older forms in existing code.

1. The App trait (Scala 2 and 3):

SCALA
object Hello extends App:
  println("Hello, World!")

This works, but the body runs in an initializer, which has caveats with threads and values that are initialized late. Scala 3 deprecates it in favour of @main.

2. The classic main method:

SCALA
object Hello:
  def main(args: Array[String]): Unit =
    println("Hello, World!")

This is the Java-compatible form and still works everywhere. Scala 2 required it. Prefer @main for new Scala 3 code.

A slightly bigger program

Here is a program that uses a value, a method and a loop:

SCALA
def square(n: Int): Int = n * n

@main def squares(): Unit =
  for i <- 1 to 5 do
    println(s"$i squared is ${square(i)}")
TEXT
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

1 to 5 makes an inclusive range, for ... do repeats the body, and ${...} inside an s"..." string embeds an expression. The same loop in Java:

Java Squares in Java

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common beginner mistakes

  • Forgetting = after the signature. def hello(): Unit without = declares an abstract method, not a body.
  • Mixing tabs and spaces. Indentation is meaningful in Scala 3. Use spaces (two is the convention) and keep it consistent.
  • Two @main methods with the same name in one project fail to compile. Give each a unique name.
  • Expecting a class named after the file. The file name does not need to match anything.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the @main annotation do?

    @main tells the compiler to generate the JVM entry point that calls your method.
  2. 2. What is the type Unit closest to in Java?

    Unit is Scala's type for a method that returns no useful value, similar to void.
  3. 3. Which entry-point style is recommended for new Scala 3 code?

    @main is simpler and avoids the initialization pitfalls of the App trait, which Scala 3 deprecates.
  4. 4. How are arguments after -- handled by a @main def add(a: Int, b: Int)?

    The generated entry point parses the strings into the declared parameter types.

Summary

  • @main def name(): Unit = ... is the Scala 3 way to write a program.
  • Indentation replaces braces; semicolons are optional and rarely used.
  • println prints with a newline; Unit means no useful result.
  • @main parameters are parsed from the command line.
  • object X extends App and def main(args: Array[String]) still work but are older styles.

Next: Syntax Rules and Comments