Scala Output
Output is the text a program shows on the screen when it runs. Scala prints output with println, which moves to a new line, and print, which stays on the same line.
Each println starts a new line
Two println commands give two separate lines. The second value never joins the first line.
@main def main(): Unit =
println("First")
println("Second")Three print commands build one line
Each print command stays on the same line. The three pieces join into one line of output.
@main def main(): Unit =
print("Scala ")
print("is ")
print("fun")An empty println prints a blank line
The middle println has no value inside its brackets. It prints an empty line between the two words.
@main def main(): Unit =
println("First")
println()
println("Last")Example
@main def main(): Unit =
println("Report")
println()
print("Scala ")
print("prints ")
println("here")Key points
- println: println prints a value and then moves to a new line.
- print: print prints a value and stays on the same line.
- Order: printed pieces appear in the order the print commands run.
- Blank line: println with nothing inside its brackets prints an empty line.
- Numbers: println and print can show numbers as well as text.
In this example, the first line prints the title Report. The empty println adds a blank line, and the two print commands plus the final println build the last line piece by piece.
Note
in Scala, print without ln at the end is the command that leaves the line open.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
Which command prints a value and stays on the same line?