valitems=setOf("apple","banana","kiwifruit")when{"orange"initems->println("juicy")"apple"initems->println("apple is fine too")}// -> apple is fine too
1 2 3 4 5 6 7
valfruits=listOf("banana","avocado","apple","kiwifruit")fruits.filter{it.startsWith("a")}.sortedBy{it}.map{it.toUpperCase()}.forEach{println(it)}// -> APPLE AVOCADO
Nullable values and null checks
Return null if str does not hold an integer
1 2 3
funparseInt(str:String):Int?{// ...}
1 2 3 4 5 6 7 8 9 10 11 12 13
funprintProduct(arg1:String,arg2:String){valx=parseInt(arg1)valy=parseInt(arg2)// Using `x * y` yields error because they may hold nulls.if(x!=null&&y!=null){// x and y are automatically cast to non-nullable after null checkprintln(x*y)}else{println("'$arg1' or '$arg2' is not a number")}}
Type checks and automatic casts
1 2 3 4 5 6 7 8 9
fungetStringLength(obj:Any):Int?{if(objisString){// `obj` is automatically cast to `String` in this branchreturnobj.length}// `obj` is still of type `Any` outside of the type-checked branchreturnnull;}