Declaring variables
You declare a variable in Kotlin with the val keyword, the name of the variable, the datatype,
and then the actual value the variable will hold.
// val name: dataType = actual value;val count: Int = 2To reference a variable in a string, you use the $ symbol.
fun main(){ val count: Int = 2 println("You have $count unread messages")}Type inference
Instead of specifying the datatype of the variable, we can just declare the variable directly and the compiler will infer the type for you.
val count = 2 // the compiler will infer this as an intIf you need to update the value of a variable, declare it with the Kotlin keyword var, instead
of val.
val— use when you expect the variable value will not change (fixed value).var— use when you expect the variable value can change (mutable value).
In Kotlin, it’s preferred to use val over var because it’s safer and more predictable.
fun main(){ var cartTotal = 0 cartTotal = 20 println("Your cart total is $cartTotal")}Arrays
To create arrays in Kotlin, you can use functions such as arrayOf(), arrayOfNulls(), or
emptyArray(), or the Array constructor.
val numbers = arrayOf(1, 2, 3, 4, 5)println(numbers.joinToString()) // 1, 2, 3, 4, 5println(numbers[0]) // 1Similarly, you can use arrayOfNulls():
val nullArray: Array<Int?> = arrayOfNulls(5)println(nullArray.joinToString()) // null, null, null, null, nullEmpty arrays can be created with:
var exampleArray = emptyArray<Int>()The Array constructor takes the array size and a function that returns values for array
elements given its index:
val initArray = Array<Int>(3) { 0 }println(initArray.joinToString()) // 0, 0, 0
// creates an Array<String> with values ["0", "1", "2"]val asc = Array(3) { i -> (i * i ).toString()}asc.forEach { println(it) }To check whether two arrays have the same elements, you can use the contentEquals() and
contentDeepEquals() functions:
val simpleArray = arrayOf(1, 2, 3)val simpleArray2 = arrayOf(1, 2, 3)
println(simpleArray.contentEquals(simpleArray2)) // true