Learn/Scala/1. Hello, output
Lesson 1 of 8
Sign in

Scala, lesson 1

Hello, output

Every Scala program needs a place to start. In Scala 3 you mark that place with the @main annotation. The method under it becomes the program's entry point: when you press Run, Scala calls it, and the lines inside run from top to bottom.

Let's read it piece by piece:

  • def hello() defines a method called hello with no parameters.
  • : Unit is the return type. Unit means "returns nothing useful", like void in other languages.
  • = starts the body. Scala 3 uses indentation to show which lines belong to the body, so keep them lined up with two spaces.
  • println(...) prints a value followed by a new line.

2 exercises to try what you just read.

Exercise 1

Your first program

Press Ctrl Enter or Check to test your code.

Exercise 2

A shop sign

Press Ctrl Enter or Check to test your code.

println and print

println ends the line for you. print does not, so the next output continues on the same line. That is handy when you build one line out of several pieces:

println accepts any value, not only text. Numbers, booleans and lists are turned into text automatically.

Strings

Text between double quotes is a String. Inside a string, a backslash starts an escape sequence: \n is a new line, \t is a tab, and \" is a double quote that does not end the string.

Single quotes are for one character ('A'), which is a different type called Char, so use double quotes for text.

Comments

Comments are notes for people. Scala ignores them.

How a Scala program runs

Scala is a compiled language. Before your program runs, the compiler reads the whole file, checks the types, and turns it into bytecode for the Java Virtual Machine. If something is wrong, such as a missing quote, you get a compile error with a line number, and nothing runs at all. Read the message carefully: it usually points right at the problem. Compiling takes a few seconds, so don't worry if Run feels slower than in Python.

Further reading

  • Scala 3 Book: Hello, World!
  • Scala 3 Book: Main methods
  • Scala 3 Book: A Taste of Scala (comments)

Write a program that prints exactly these two lines:

The program reads no input.

Print this sign for a coffee shop. The middle line must be built with three print calls ("Open", " 7am", " - 6pm") followed by one println() to end the line.

@main def hello(): Unit =
  println("Hello, World!")
  println("Scala runs these lines in order.")
@main def progress(): Unit =
  print("Loading")
  print("...")
  println("done")      // Loading...done
  println()            // an empty line
  println(40 + 2)      // 42
println("Line one\nLine two")
println("She said \"hi\"")
// A line comment runs to the end of the line.

/* A block comment
   can span several lines. */
println("Comments are skipped") // this one follows code
Hello, World!
I am learning Scala.
+--------------+
Open 7am - 6pm
+--------------+