Kotlin miniguide #16 Null safety

Unless explicitly declared, a reference in kotlin cannot hold the value null

When a reference is nullable, a check on the reference must be done before accessing the object, otherwise we will get a compiler error:


var s : String = "a"

s = null //<strong>does not compile </strong>

var p: String? = "a"

p = null //<strong>ok</strong>

p.lenght //<strong>does not compile </strong>

p?.length //<strong>ok</strong>

Kotlin miniguide #15 Collections

Create and filter a read only list:


var comics = listOf(Comics("Akira", "Japan" ), Comics ("Nausicaa", "Japan" ), Comics ("Spiderman", "Usa" ))

var titles = comics.filter ( it == "Japan")

.map(m ->m.title)

//titles will contain Akira and Nausicaa

class Comics (title : String, nation : String )

For adding or removing elements, we must use mutableListOf

A nice page about collections

Kotlin miniguide #14 High order functions

In Kotlin, functions can be passed as arguments to other functions, returned from functions, stored in variables.

In the code below a function add is declared as a lambda and passed as argument to the function calc:


val add ={a: Int, b: Int ->a+ b}

fun calc(i1:Int, i2: Int, action : (p1: Int, p2: Int) -> Int) {

var result = action (i1, i2)

}

//usage

calc(add)

In the code below a function add is declared as an anonymous function and passed as argument to the function calc:


val add =fun(a: Int, b: Int) =a+ b

fun calc(i1:Int, i2: Int, action : (p1: Int, p2: Int) -> Int) {

var result = action (i1, i2)

}

//usage

calc(add)

Returning a function that accepts a string and returns nothing:


fun displaMsg(msg : String) : (String) -> Unit {

return { s -> println ("$msg is $s" ) }

}

val d = displayMsg("error")

d("401")

//output is "error is 401"

Kotlin miniguide #13 Data classes

For classes that contain only data, Kotlin provides an implementation of

  • equals
  • getHashCode
  • toString
  • copy

Consider the following examples


class Person (name : String)

Person a = Person ("Tom")

Person b = Person ("Tom")

println(a == b)

this print false because equals compares the objects references.

If instead we use a data class:


data class Person (name : String)

Person a = Person ("Tom")

Person b = Person ("Tom")

println(a == b)

this print true because equals is called on each member, and in this case the two instances have the same name.

It is possible to copy an instance of a data class changing some of its properties:


class Person (name : String, age : Int)

Person a = Person ("Tom", 23)

Person b = a.copy(age = 35)