Arrays
Store a list of numbers in one variable.
1fun main() {
2 val numbers = intArrayOf(1, 2, 3)
3 println(numbers.contentToString())
4}
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
[1, 2, 3]
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 numbers = intArrayOf(1, 2, 3)- intArrayOf(...) makes an array: a list of values stored in a single variable. Every item must be the same type (here whole numbers, Ints). You read items back by their index, which starts at 0: numbers[0] is 1, numbers[1] is 2 and numbers[2] is 3.
println(numbers.contentToString())- Careful: printing an array directly, println(arr), does NOT show its contents in Kotlin! It prints a strange code like [I@1b6d3586 (the exact letters depend on the array's type). arr.contentToString() turns the array into readable text like [1, 2, 3] first, and that is what we print.
}- This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.