splimter
12/18/2019 - 1:27 PM

kotlin quick notes

kotlin quick notes

Basic

Variables

  • val is const while var is dynamic type.
  • declar var: var x:Type = initVal.
  • if x must be null then: var x:Type? = initVal.
  • kotlin support type interference: var x = initVal, no way to assing null.
  • when is like switch:
when(x){
    null -> print("its null")
    else -> print("hello")
}
  • ugly ternary var y = if(x!=null) x else "smtg".
  • ternary var y = x ?: "smtg".
  • array are defined by 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").
  • iterator
    • for (ar in arr){ println(ar) }.
    • arr.forEach { i -> print(i) }.
    • arr.forEach { print(it) }.
    • arr.forEachIndexed { index, str -> println("$index is $str") }

Function

  • 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

  • class Person constructor() same as class Person
  • set class with ctor:
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}")
  • custom action on set:
// 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} ")
  • By default the visibility is public.
  • internal class only visible on same module
  • cast type as otherType