Collection Kotlin

Filter Map

fun main(args: Array<String>) { val myNumbers: List<Int> = listOf(2, 3, 4, 6, 23, 90) val mySmallNums = myNumbers.filter { it < 10 } // OR { num -> num < 10 } for (num in mySmallNums) { println(num) } val mySquaredNums = myNumbers.map { it * it } // OR { num -> num * num } for (num in mySquaredNums) { println(num) } var people = listOf<Pperson>(Pperson(10, "Steve"), Pperson(23, "Annie"), Pperson(17, "Sam")) var names = people.filter { person ->person.name.startsWith("S") }.map { it.name } for (name in names) { println(name) } } class Person(var age: Int, var name: String) { // Some other code.. }

Filter

You can filter the data, like a string startWith("S")

Map

You can do actions like + * / %

Null safety

// WAP to find out length of name val name: String? = "Steve" // change it to null and see the effect in output // 1. Safe Call ( ?. ) // Returns the length if 'name' is not null else returns NULL // Use it if you don't mind getting NULL value println("The length of name is ${name?.length}") // 2. Safe Call with let ( ?.let ) // It executes the block ONLY IF name is NOT NULL name?.let { println("The length of name is ${name.length}") } // 3. Elvis-operator ( ?: ) // When we have nullable reference 'name', we can say "is name is not null", use it, // otherwise use some non-null value" val len = if (name != null) name.length else -1 val length = name?.length ?: -1 println("The length of name is ${length}") // 4. Non-null assertion operator ( !! ) // Use it when you are sure the value is NOT NULL // Throws NullPointerException if the value is found to be NULL println("The length of name is ${name!!.length}")

lateinit

fun main(args: Array<String>) { val country = Country() // country.name = "India" // println(country.name) country.setup() } class Country { lateinit var name: String fun setup() { name = "USA" println("The name of country is $name") } }

// lateinit used only with mutable data type [ var ]

lateinit used only with non-nullable data type

lateinit values must be initialised before you use it

If you try to access lateinit variable without initializing it then it throws UninitializedPropertyAccessException

lateinit

val pi: Float by lazy { 3.14f } fun main(args: Array<String>) { println("Some initial code.....") // pi is not initialised yet val area1 = pi * 4 * 4 // pi gets initialised and assigned the value of 3.14f for the first time val area2 = pi * 9 * 9 // The value pi is loaded from cache memory println("Some more code....") }

‘lazy initialization’ was designed to prevent unnecessary initialization of objects.

You variables will not be initialised unless you use it in your code

It is initialized only once. Next time when you use it, you get the value from cache memory.

It is thread safe

It is initialized in the thread where it is used for the first time.

Other threads use the same value stored in the cache

The variable can be var or val.

The variable can be nullable or non-nullable