In this presentation, Segun and I introduced the audience to Kotlin. We spoke about the history, the exciting new features and how to get started with learning it.
Awesome features - nullable types, concise, data classes, etc. Great community support There was an overwhelming request for Kotlin official support on Android
error var name: String name = null // compiler error var name: String? val length = name.length A non-nullable object can’t be null Protects against NullPointerException the $1,000,000,000 mistake Specify a nullable object by using “?” Kotlin ensures that you don’t mistakenly operate on nullable objects
use ?. to make safe call var name: String? = null ... val length = name?.length Use ?. to safely access a property/method on a nullable object If name happens to be null, the value of length is 0 (inferred integer). length would be null if it were of another type. 2. Making safe calls using “?.”
use elvis operator var name: String? = null val length = name?.length ?: 0 This reads as “if name is not null, use name.length else use 0” 3. Making use of the “?:” elvis operator
use !! assertion var name: String? = null val length = name!!.length This reads as “if name is not null, use name.length else throw a null pointer exception” 4. Making use of the “!!” assertion operator
type val name = "Segun" // string val age = 24 // int val grade = 'A' // char val hobbies = listOf("karate", "eating") // list of strings Kotlin can smartly infer the type of your variable from the data it contains
simply means that things you create can’t be changed. We need immutability because it: • helps us with thread safety - no synchronization issues • is good for value objects - objects that simply hold value, POJOs etc. • helps debugging threaded applications without losing your hair
final int age; public ImmutableClassJava(String name, int age) { this.name = name; this.age = age; } // no setters public String getName() { return name; } public int getAge() { return age; } } class ImmutableClass(val name: String, val age: Int, val grade: Char, val hobbies: List<String>) • Class is final by default • val implies that the parameters are final as well (values can’t be assigned) Immutability in Java vs Kotlin
here } // function with param fun sampleFuncWithParam(param: String) { // code goes here } A function is declared using the “fun” keyword Method parameters use the “name:Type” notation
here } // function with param fun sampleFuncWithParam(param: String) { // code goes here } // func with param and return type fun capitalize(param: String): String { return param.toUpperCase() } Method parameters use the “name:Type” notation Return types are specified after the method definition. A function is declared using the “fun” keyword
• Clone the project on Github IDE support Community Kotlin Weekly http://www.kotlinweekly.net/ Kotlin Conf kotlinconf.com + = built-in support plugin = built-in support