Learn/Kotlin/1. Hello, output
Lesson 1 of 8
Sign in

Kotlin, lesson 1

Hello, output

Every Kotlin program starts in a function called main. When you run the program, Kotlin calls main for you and runs the statements inside its curly braces, one after another.

fun declares a function, main is its name, and the empty parentheses mean it takes no arguments. Everything between { and } is the function's body. Unlike some languages, Kotlin does not need a semicolon at the end of each line.

Text in double quotes is a string. Kotlin strings always use double quotes; single quotes are for a single character, like 'A'.

println and print

println() writes a value and then moves to a new line. writes the value and stays on the same line, so the next output continues right after it.

2 exercises to try what you just read.

Exercise 1

Your first program

Press Ctrl Enter or Check to test your code.

Exercise 2

A countdown banner

Press Ctrl Enter or Check to test your code.

print()

println() with nothing inside just prints a line break, which is handy for spacing out output.

Putting values inside strings

You can drop a value straight into a string with a string template. Write $ followed by a name, or ${...} around any expression:

You will use templates constantly once you have variables, which is the next lesson.

Comments

Comments are notes for people; the compiler skips them. Kotlin has two kinds:

Block comments can even be nested inside each other, which makes it easy to comment out a chunk of code that already contains a comment.

How a program runs

Kotlin is a compiled language. Before anything runs, the compiler reads your whole file and checks it. If something is wrong, such as a missing quote or a misspelled println, you get a compile error with a line number and nothing runs at all. Compiling Kotlin takes a few seconds, so don't worry if the first run feels slow. Once the program compiles, main runs from its first statement to its last.

Further reading

  • Kotlin docs: Basic syntax
  • Kotlin docs: Strings and string templates

Write a program that prints exactly these two lines:

The program reads no input.

Print a launch countdown on one line using three print() calls, then print Liftoff! on the next line with println(). Finally, use a string template to print the sum of 7 and 5 inside a sentence.

Expected output:

fun main() {
    println("Hello, World!")
    println("Kotlin starts in main and runs top to bottom.")
}
fun main() {
    print("Loading")
    print("...")
    println("done")       // Loading...done
    println(42)           // numbers work too
    println()             // an empty line
}
fun main() {
    println("2 + 3 = ${2 + 3}")   // 2 + 3 = 5
}
// A line comment runs to the end of the line.

/* A block comment can span
   several lines. */

fun main() {
    println("Comments are ignored") // this part is ignored too
}
Hello, World!
I am learning Kotlin.
3...2...1...
Liftoff!
Seats on board: 12