Kotlin Output
Printing text is how your program talks to you. Kotlin has two printing functions in its standard library: println() and print().
println()
println prints its argument and then moves to a new line. You can print text, numbers, the results of calculations and more:
fun main() {
println("Coffee order")
println(3)
println(2.5 * 4)
println(true)
}Coffee order
3
10.0
true
Calling println() with no argument prints an empty line — handy for spacing.
print()
print writes its argument without a line break, so the next output continues on the same line:
fun main() {
print("Loading")
print(".")
print(".")
println(".")
println("Done!")
}Loading...
Done!
| Function | Adds a line break? | Typical use |
|---|---|---|
println(x) |
yes, after x |
most output |
print(x) |
no | building a line piece by piece |
println() |
yes (prints only the break) | empty line |
Combining text and values
You can glue strings together with +, but the Kotlin way is a string template: write $name or ${expression} inside the string.
fun main() {
val item = "latte"
val price = 3.5
val cups = 2
println("Item: " + item)
println("You ordered $cups $item drinks")
println("Total: ${price * cups} EUR")
}Item: latte
You ordered 2 latte drinks
Total: 7.0 EUR
Use ${...} whenever the template contains more than a simple variable name — a calculation, a property like ${item.length}, or a function call.
Escape sequences
Some characters need a backslash inside a string:
| Sequence | Meaning |
|---|---|
\n |
new line |
\t |
tab |
\" |
double quote |
\\ |
backslash |
\$ |
a literal dollar sign |
fun main() {
println("Name\tQty")
println("Tea\t2\nCake\t1")
println("She said \"hi\" and paid \$5")
}Name Qty
Tea 2
Cake 1
She said "hi" and paid $5
Multi-line text
A raw string uses three quotes. It can span lines and doesn't process escapes; trimIndent() removes the common leading indentation:
fun main() {
val receipt = """
==========
THANK YOU
==========
""".trimIndent()
println(receipt)
}==========
THANK YOU
==========
Note: On the JVM,
printlnwrites to standard output. Error messages are usually written to standard error withSystem.err.println(...).
Test yourself
What is the difference between print and println?
printis fasterprintlnadds a line break after the output,printdoesn'tprintonly works with strings- There is no difference
What does println("Sum: ${2 + 3}") print?
- Sum: ${2 + 3}
- Sum: 2 + 3
- Sum: 5
- Sum: 23
How do you print a literal dollar sign before a variable name?
- $name
- $name
- '