Learn Scala 3 Fast: Printing With println

The next important thing to know is how to print output to the command line. This lets you see the output of your calculations, and in Scala we do this with the println function:

println("Hello, world")

In that code, this text is a string — an instance of the Scala String class:

"Hello, world"

We call it a string because it’s a string of characters.

As shown in that code, strings are enclosed in double-quotes. When you run that code in the REPL, it prints the string Hello, world to the command line.

NOTE: Technically what it really does is print your string, followed by a newline character.

As with other programming languages you can concatenate two strings together with the + operator, like this:

println("Hello," + " world")

Both of those println statements print the same output.

NOTE: As shown, you can use the + symbol to concatenate two strings, but there’s a better way to do this, and you’ll see that better approach shortly.

print

As mentioned, println prints your string, followed by a newline character. When you want to print a string that is not followed by a newline character, use print instead:

print("Hello, world")

There’s no easy way for you to confirm yet that what I just wrote is true, but you can adjust some scripts later to use print instead of println so you can see the difference.

STDOUT and STDERR

Technically, the println function prints a string to “standard output,” which is also known in the computer world as “STDOUT.” In a script or command-line application this means that the string is printed to the command line. If instead you want to print a string to standard error (STDERR) — typically for error messages — use this function instead:

System.err.println("An error message")

In the Unix world you can redirect STDOUT and STDERR to different locations, so it’s important to note this distinction.

Exercises

The exercises for this lesson are available here.