kotlin quick notes
val
is const while var
is dynamic type.var x:Type = initVal
.var x:Type? = initVal
.var x = initVal
, no way to assing null.when(x){
null -> print("its null")
else -> print("hello")
}
var y = if(x!=null) x else "smtg"
.var y = x ?: "smtg"
.arrayOf()
: var arr = arrayOf(1,2,3,4,5)
,
map are defined by val mp = mapOf(1 to "a", 2 to "b", 3 to "c")
.for (ar in arr){ println(ar) }
.arr.forEach { i -> print(i) }
.arr.forEach { print(it) }
.arr.forEachIndexed { index, str -> println("$index is $str") }
Unit
is like void
fun x(): Unit {}
fun y(): String { return "str" }
// shorthand for y as it has single ins
fun y(): String = "str"
fun y(msg:String): String { return msg }
// to call
y("hi") // y(msg = "hi") must name them all
// vararg: take multi-String
fun xy(pramStr:String,vararg pramArr:String){
println(pramStr)
pramArr.forEach { println(it) }
}
// to call: arr is arrayOf(str)
xy("Hello","am a","am b","am c")
xy("Hello",*arr)
// Default param y("hi") | y()
fun y(msg:String="default"): String { return msg }
class Person constructor()
same as class Person
class Person(_fname:String, _lname:String){
val fname:String = _fname
val lname:String = _lname
}
to call:
var pr = Person("hi","ho")
pr.fname = "soheyb"
pr.lname = "merah"
println("${pr.fname} ${pr.lname}")
// in a class
var nickname:String? = null
set(value) {
field = value
field = "($value)"
}
// invoke pr.nickname = "me"
get() {
println("using getter $field")
return field
}
// invoke println("${pr.nickname} ")
internal class
only visible on same moduletype as otherType