if…else在Java是语句,而在Kotlin中可以做为表达式使用
三元表达式
c = a == 3? 4: 5;
c = if(a==3) 4 else 5
,为if…else表达式switch
switch(a) {// Java代码 case 0: c = 5; break; case 1: c = 100; break; default: c = 20; }
when(a) { 0 -> c = 5 1 -> c = 100 else -> c = 20 }
\\ 上面式子也可写成 c = when(a) { 0 -> 5 1 -> 100 else -> 20 }
\\ 把条件转移到分支 var x: Any = ... when { x is String -> c = x.length// x智能转换成String x == 1 -> c = 100 else -> c = 20 } // 也可以写成 c = when { x is String -> x.length// x智能转换成String x == 1 -> 100 else -> 20 }
c = when(val input = readLine()) { null -> 0 else -> input.length }
try…catch
// Java代码 try { c = a / b; } catch(Exception e) { e.printStackTrace(); c = 0; }
// Kotlin代码 try { c = a / b } catch(e: Exception) { e.printStackTrace() c = 0 }
// Kotlin代码 c = try { a / b } catch(e: Exception) { e.printStackTrace() 0 }
好多耳熟能详的语句在Kotlin中全是表达式,有返回值的