Scala 3 · 37 of 42

Top-level definitions & @main

In Scala 2, everything had to live inside a class, trait, or object. A simple script meant ceremony:

object Main {
  def main(args: Array[String]): Unit = {
    println("Hello!")
  }
}

Scala 3 removes both layers of ceremony:

  • Top-level definitions: vals, defs, type aliases, and givens can sit directly in a file, next to your classes. (This replaces Scala 2’s “package objects”, which are being phased out.)
  • @main methods: any method annotated with @main becomes a program entry point. Its parameters become command-line arguments, parsed for you:
@main def greet(name: String, times: Int) =
  for _ <- 1 to times do println(s"Hello, $name!")

Running scala run . -- Alice 3 prints the greeting three times; no Array[String] in sight.

Note: the editor here runs in worksheet mode: your code is already inside a script, so @main is shown in a comment (a worksheet has no place for a program entry point; a plain .scala file does).
//In Scala 3, definitions can live directly at the top of a file;
//no wrapper object needed.

val language = "Scala 3"

def welcome(name: String) = s"Welcome to $language, $name!"

case class User(name: String)

println(welcome(User("Alice").name))

//In a real .scala file, an entry point is just an annotated method:
//  @main def run(): Unit = println(welcome("world"))
//(this worksheet already runs top-to-bottom like a script,
// so here we just call the method directly)
def run(): Unit = println(welcome("world"))
run()

Contents

Scala basics

  1. Overview
  2. Scalculator
  3. Operators are methods
  4. Variables
  5. Final variables
  6. Printing values
  7. String interpolation
  8. String formatting
  9. Useful operations
  10. Method definition
  11. Method definition 2
  12. Method definition 3
  13. Anonymous functions
  14. Anonymous functions 2
  15. Return multiple values
  16. Declare multiple variables
  17. Assign multiple variables
  18. Loops using while
  19. Loops using for
  20. Loops without loops
  21. If
  22. Match as a switch
  23. Arrays
  24. Lists
  25. Sets
  26. Maps
  27. Mutable collections
  28. Collections: accessing elements
  29. Collections: concatenation
  30. Mutable collection operations
  31. Immutable collections with var
  32. Collections: useful methods
  33. Classes
  34. Classes, continued

What's new in Scala 3

  1. Scala 3: what changed
  2. Optional braces & new control syntax
  3. Top-level definitions & @main
  4. Enums & ADTs
  5. Extension methods
  6. given & using
  7. Union & intersection types
  8. Smaller niceties