Line At A Time
Lesson 5: String and Number
String and Number Drop variables straight into text with a string template.
1fun main() {
2 val ten = 10
3 val label = "ten"
4 println("$ten$label")
5}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
10ten
Every line, explained
fun main() {
Every Kotlin program starts at the main function. When you run the program, Kotlin looks for fun main() and runs everything between its { and } from top to bottom.
val ten = 10
val creates a read-only variable: a named box whose value is set once and then never changes. Kotlin people reach for val by default, and only switch to var when a value truly needs to change. Notice there is no type word like Int: Kotlin sees the value and works out the type for you. This is called type inference.
val label = "ten"
A String is a piece of text. In Kotlin text always goes inside double quotes: "like this". Single quotes are only for one single character (like 'A'), so writing 'Hello' would be an error.
println("$ten$label")
Inside a Kotlin string, a $ in front of a variable name is swapped for that variable's value. This is called a string template. So "$ten$label" becomes "10" then "ten", printing 10ten. It is the tidy Kotlin way to mix variables into text.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.