Kotlin Tutorial · Kotlin Basics · Lesson 3 of 31
Kotlin Syntax and Output
Statements, comments, println and print, and string templates for formatted output.
Basic syntax
- One statement per line, no semicolons needed.
//line comments and/* ... */block comments (which can nest).println(x)prints a value and a new line;print(x)prints without the new line.
fun main() {
// Print a few values
print("Loading")
print("...")
println(" done")
println(42)
println(3 * 7 + 1)
}
Output
Loading... done 42 22
Run this on your computer — see “Get Started” for setup.
String templates
$name inserts a variable and ${expression} inserts any expression. "%.2f".format(x) formats numbers.
fun main() {
val name = "Ana"
val items = listOf("mug", "teapot")
val balance = 1234.5678
println("$name has ${items.size} items")
println("First item: ${items.first().uppercase()}")
println("Balance: ${"%.2f".format(balance)} EUR")
}
Output
Ana has 2 items First item: MUG Balance: 1234.57 EUR
Run this on your computer — see “Get Started” for setup.
Test yourself
How do you insert the result of an expression into a string?
$(expression)${expression}{expression}%expression%
Show answer
Answer: ${expression}