TExcelTAD
Home › Kotlin › Kotlin Output

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:

kotlin · try it yourself
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:

kotlin · try it yourself
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.

kotlin · try it yourself
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
kotlin · try it yourself
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:

kotlin · try it yourself
fun main() {
    val receipt = """
        ==========
         THANK YOU
        ==========
    """.trimIndent()
    println(receipt)
}
==========
 THANK YOU
==========

Note: On the JVM, println writes to standard output. Error messages are usually written to standard error with System.err.println(...).

Test yourself

What is the difference between print and println?

  1. print is faster
  2. println adds a line break after the output, print doesn't
  3. print only works with strings
  4. There is no difference

What does println("Sum: ${2 + 3}") print?

  1. Sum: ${2 + 3}
  2. Sum: 2 + 3
  3. Sum: 5
  4. Sum: 23

How do you print a literal dollar sign before a variable name?

  1. $name
  2. $name
  3. ' name
  4. #$name