Kotlin, lesson 1
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() 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.
print()println() with nothing inside just prints a line break, which is handy for spacing out output.
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 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.
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.
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