//compilation error var b: String? = null // OK! b = bob?.department?.name // safe chained calls val l = b!!.length() // YOYO (NPE-lovers) // default value if var is null val l = b?.length ?: -1
package fun Int.beforeKitkat()= this < Build.VERSION_CODES.KITKAT // usage in Kotlin if (Build.VERSION.SDK_INT.beforeKitkat()){ // do something… } extend function name caller return type is inferred Usage in Kotlin
package fun Int.beforeKitkat()= this < Build.VERSION_CODES.KITKAT Just like helper method in Java // usage in Java if (com.nevin.MyHelperKt.beforeKitkat(Build.VERSION.SDK_INT)){ // do something… }
or x == 1”) 2 -> print("x == 2") true -> print("true") is String -> x.startsWith("prefix") is File -> x.getFreeSpace() else -> { // Note the block print("x is funny") } } No need to cast again
Main constructor must be called • Parent’s constructor must be called class MyView : View { constructor(ctx: Context) : super(ctx) { } constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs) { } } default constructor must called
Int { return x + y } // function expression val sum = fun(x: Int, y: Int): Int { return x + y } // one liner val sum = fun(x: Int, y: Int): Int = x + y
Int { return x + y } // function expression val sum = fun(x: Int, y: Int): Int { return x + y } // one liner val sum = fun(x: Int, y: Int): Int = x + y
or return a function fun calculate(x: Int, y: Int, formula: { } (Int, Int) -> Int println("the result is ${formula(x, y)}") // usage fun main(args: Array<String>) { calculate(1,5, ) calculate(1,5, ) } sum { x, y -> x + y }
,run(), use() • Not a completely new language, very handy • A great place to learn functional programming • Droidcon talks may not up-to-date. Some issues are fixed.
use inheritance with data class • Pass in function instead of object • Almost everything in Kotlin is an expression ( can return value) • Just “convert Java code to Kotlin” and “Config Kotlin in Project”
Koans web and github • Jake Wharton : Using Project Kotlin for Android and Advancing Development with the Kotlin • twitter #kotlin @cbeust @madisp [JRebel] • Links : antonio leva , Jcconf 2015