print and println
The fastest way to see what your program is doing is to make it talk. For the café, that might be a receipt on the screen or a quick check that a total is what you expect. Kotlin gives you two functions for this, and they differ by exactly one character: a new line.
The rule
println ends the line; print leaves the cursor waiting.
println("Pebble Café")
print("Latte")
print(" x")
println(2)
println()
println("Thanks!")Output:
Pebble Café
Latte x2
Thanks!println(value)writes the value, then a line break.print(value)writes the value and stays on the same line.println()with nothing inside writes only a line break, giving a blank line.
Both accept any value, not just strings. They call the value's toString() to turn it into text:
println(3.5) // 3.5
println(true) // true
println(listOf("latte", "chai")) // [latte, chai]
println('A') // ALists, sets and maps print their contents nicely. Arrays do not: println(arrayOf(1, 2)) shows something like [Ljava.lang.Integer;@1b6d3586. Use arrayOf(1, 2).contentToString() to see [1, 2].
Both functions are available everywhere without an import, because they live in kotlin.io, a default import. There is also readln() for reading one line of text typed by the user.
The shortcut
Track an imaginary cursor. Each print moves it right; each println moves it right and then down to the start of the next line. Draw the output by following the cursor.
print("Cups: ")Screen:
Cups:and the cursor stays at the end of that line.
A common slip is ending a program with print. The last line may then run straight into the terminal prompt that follows it.
Drills
Answer fast — trust the rule.
How many lines does print("a"); print("b"); println("c") produce?
What does println() with no argument do?
What does println(listOf(2, 4)) print?
How do you print the contents of val cups = arrayOf(1, 2, 3)?
Remember
printlnadds a line break;printdoes not;println()alone makes a blank line.- Any value can be printed through its
toString(). - Follow the cursor to predict the output; arrays need
contentToString().
