Collection which includes list, set, and map are resizeable.
IntArray stores primitive and unboxed items. Array<Int> and collection stores boxed types.
To-the-power-of operator
Manual
funpow(base: Int, exponent: Int): Long {
varresult: Long = 1while (exponent != 0) {
result *= base.toLong()
--exponent
}
returnresult
}
pow() from Math class
Math.pow(base.toDouble(), exponent.toDouble())
Pre and post increment
++aincrementsandthenreturnsthevariablea++ returnsandthenincrementsthevariablevara = 1println(a++); //You will see 1//Now a is 2println(++a); //You will see 3
Structural Jump Expressions (return, break, and continue)
return - returns from the nearest enclosing function or anonymous function
break - terminates the nearest enclosing loop
continue - skip remaining and continue with next step or proceeds to the next step of the nearest enclosing loop
here@for (iin1..5) {
for (jin1..4) {
if (i == 3 || j == 2)
continue@hereprintln("i = $i; j = $j")
}
}
Map<K, V>
Doesn’t inherit Collection interface but is Kotlin Collection type.
Stores key-value pairs. Keys are unique.
Map (immutable)
// creates an immutable map without write operationsvalnumbersMap = mapOf("key1"to1, "key2"to2, "key3"to3, "key4"to1)
println(numbersMap.get("1"))
println(numbersMap["key1"])
println(numbersMap.getOrDefault("key5", 0)) // return default if key not foundprintln("${numbersMap.keys}") // [key1, key2, key3, key4]println("${numbersMap.values}") // [1, 2, 3, 1]if ("key2"innumbersMap) // return true if key2 is foundif (1innumbersMap.values) // returns true if value 1 is in the mapif (numbersMap.containsKey(key)) // same as previousif (numbersMap.containsValue(1)) // same as previousfor ((k, v) innumbersMap) // returns the pair if foundprintln("Entries: " + numbersMap.entries) // Entries: [key1=1, key2=2, key3=3, keys4=1]println("Keys:" + numbersMap.keys) // Keys:[key1, key2, key3, key4]println("Values:" + numbersMap.values) // Values:[1, 2, 3, 1]
MutableMap (Mutable or with write operation)
// creates an immutable map without write operationsvalnumbersMap = mutableMapOf("key1"to1, "key2"to2, "key3"to3)
numbersMap.put("key4", 1)
numbersMap["key4"] = 1numbersMap.remove("key1") // remove a pairnumbersMap.clear() // remove all pair
HashMap
Default implementation is LinkedHashMap which preserves insertion order