no need to cast again when (x) { is String -> x.length() is File -> x.getFreeSpace() else -> { // Note the block print("x is neither String nor File") } } // safe cast, x must be nullable val x: String? = y as? String
Prints 'true' print(a === a) // Prints ‘true' val boxedA: Int? = a val anotherBoxedA: Int? = a print(boxedA == anotherBoxedA) // 'true' print(boxedA === anotherBoxedA)// 'false'
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) { } }
print("x+y=${x + y}”) // string template fun main(args: Array<String>) { val a = A() cal(1) //default value cal(x = 3) a.cal(x = 4, y = 5) // named param }
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,sum) calculate(1,5, { x, y -> x + y }) calculate(1,5){ x, y -> x + y } calculate(1,5,fun(x: Int, y: Int): Int = x + y ) }
: let() , apply() , with() ,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 : Trending, antonio leva , Android