Kotlin 條件控制語句
條件控制是每門編程語言中必不可少的,一般就是使用我們所熟知的 if-else
,來作為我們代碼邏輯選擇條件控制。 在 Java 中一般使用 if-else
和 switch-case
來作為條件控制,而在 Kotlin 中則是使用if-else
和when
來作為條件控制。
Tips:Kotlin 中沒有
switch-case
。
1. if 表達(dá)式
1.1 帶返回值 if 表達(dá)式
在 Kotlin 中,if 是一個表達(dá)式所以它會返回一個值,表達(dá)式的值為表達(dá)式作用域內(nèi)最后一行的值。這一點(diǎn)和 Java 是不同的, 在 Java 中 if
僅僅是語句。
//一般類似java中傳統(tǒng)if的用法
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
fun main(args: Array<String>) {
println(maxOf(1, 5))
}
//作為表達(dá)式則可以這樣
fun maxOf(a: Int, b: Int) = if (a > b) a else b
fun main(args: Array<String>) {
println(maxOf(1, 5))
}
if
表達(dá)式分支可以是代碼塊,也可以把作用域內(nèi)最后一行表達(dá)式的值作為該分支塊的值:
fun maxOf(a: Int, b: Int) = if(a > b) {
println(a)
a //返回值為a
} else {
println(b)
b //返回值為b
}
fun main(args: Array<String>) {
println(maxOf(1, 5))
}
1.2 if 表達(dá)式替代三目運(yùn)算符
因為在 Kotlin 中 if
表達(dá)式是帶有返回值的,所以在 Kotlin 中是不需要三目運(yùn)算符(xxx ? xxx : xxx
), 因為if
表達(dá)式這些都能做到。
//Java中三目運(yùn)算符
public int maxOf(int a, int b) {
return a > b ? a : b;
}
而在 Kotlin 中則可以直接使用if
表達(dá)式來使用:
//Kotlin中的if表達(dá)式
fun maxOf(a: Int, b: Int) = if (a > b) a else b
Tips:如果你使用 if 作為表達(dá)式而不是語句(例如:返回它的值或者把它賦給變量),該表達(dá)式需要有
else
分支。
1.3 多級 if 表達(dá)式
和 Java 一樣 Kotlin 也支持 if-else if-else
等多級條件選擇,但是一般如果這種帶多級條件選擇的 IDE 會提示你使用 when
表達(dá)式來替代:
下面這個案例會使用 if-else if-else
來判斷變量 number 是何種數(shù)據(jù)類型:
fun eval(number: Number) {
if (number is Int) {
println("this is int number")
} else if (number is Double) {
prinln("this is double number")
} else if (number is Float) {
println("this is float number")
} else if (number is Long) {
println("this is long number")
} else if (number is Byte) {
println("this is byte number")
} else if (number is Short) {
println("this is Short number")
} else {
throw IllegalArgumentException("invalid argument")
}
}
但是需要注意的是 如果 eval 函數(shù)需要有返回值的時候,必須要有else
分支:
2. when 表達(dá)式
在 Kotlin 中使用 when
表達(dá)式替代了類似 C 語言的 switch-case
語句。其中最簡單的形式如下:
fun eval(number: Number): String = when (number) {
is Int -> "this is int number"
is Double -> "this is double number"
is Float -> "ths is float number"
is Long -> "this is long number"
is Byte -> "this is byte number"
is Short -> "this is Short number"
else -> "invalid number"
}
//多種條件判斷混合形式
fun main(args: Array<String>) {
println(descript("hello"))
}
fun descript(obj: Any): String = when (obj) {
1 -> "one"
"hello" -> "hello word"
is Long -> "long type"
!is String -> "is not String"
else -> {
"unknown type"
}
}
when 將它的參數(shù)與所有的分支條件順序比較,直到某個分支滿足條件。 when 既可以被當(dāng)做表達(dá)式使用也可以被當(dāng)做語句使用。如果它被當(dāng)做表達(dá)式, 符合條件的分支的值就是整個表達(dá)式的值,如果當(dāng)做語句使用, 則忽略個別分支的值。(像 if 一樣,每一個分支可以是一個代碼塊,它的值是塊中最后的表達(dá)式的值。)
Tips:如果其他分支都不滿足條件將會求值 else 分支。 如果 when 作為一個表達(dá)式使用,則必須有 else 分支, 除非編譯器能夠檢測出所有的可能情況都已經(jīng)覆蓋了。
如果很多分支需要用相同的方式處理,則可以把多個分支條件放在一起,用逗號分隔:
fun eval(any: Any): String = when (any) {
is Int, Double, Float, Long, Byte, Short -> "this is number" //多個分支條件放在一起,用逗號分隔
is Char -> "this is char"
else -> "other"
}
when 也可以用來取代 if-else if 鏈。 如果不提供參數(shù),所有的分支條件都是簡單的布爾表達(dá)式,而當(dāng)一個分支的條件為真時則執(zhí)行該分支:
fun eval(number: Number) {
when {
number.isOdd() -> {
println("this is odd number")
}
number.isEven() -> {
println("this is even number")
}
else -> println("this is invalid number")
}
}
3. when 表達(dá)式的功能增強(qiáng)
自從 Kotlin1.3 版本后對 when 表達(dá)式做了一個寫法上的優(yōu)化,為什么這么說呢? 僅僅就是寫法上的優(yōu)化,實際上什么都沒做. 它主要是解決什么問題呢?細(xì)心的小伙伴會發(fā)現(xiàn),在 Kotlin 1.3版本之前when
表達(dá)式內(nèi)部是不能使用傳入的值的。
3.1 Kotlin 1.3 版本之前 when
fun main(args: Array<String>) {
val value = getValue() //可以看到1.3版本之前需要多出來一步
when (value) {
is Int -> "This is Int Type, value is $value".apply(::println) //注意這里when中獲得value不是when直接傳入value,而是when外部聲明value
is String -> "This is String Type, value is $value".apply(::println)
is Double -> "This is Double Type, value is $value".apply(::println)
is Float -> "This is Float Type, value is $value".apply(::println)
else -> "unknown type".apply(::println)
}
}
fun getValue(): Any {
return 100F
}
我們可以嘗試把 kotlin 1.3 版本之前 when 表達(dá)式使用代碼反編譯成 Java 代碼:
public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
Object value = getValue();
String var3;
if (value instanceof Integer) {
var3 = "This is Int Type, value is " + value;
System.out.println(var3);
} else if (value instanceof String) {
var3 = "This is String Type, value is " + value;
System.out.println(var3);
} else if (value instanceof Double) {
var3 = "This is Double Type, value is " + value;
System.out.println(var3);
} else if (value instanceof Float) {
var3 = "This is Float Type, value is " + value;
System.out.println(var3);
} else {
var3 = "unknown type";
System.out.println(var3);
}
}
@NotNull
public static final Object getValue() {
return 100.0F;
}
3.2 Kotlin 1.3 版本之后 when
fun main(args: Array<String>) {
when (val value = getValue()) {//when表達(dá)式條件直接是一個表達(dá)式,并用value保存了返回值, 實際上相當(dāng)于把外部那一行縮進(jìn)來寫
is Int -> "This is Int Type, value is $value".apply(::println)
is String -> "This is String Type, value is $value".apply(::println)
is Double -> "This is Double Type, value is $value".apply(::println)
is Float -> "This is Float Type, value is $value".apply(::println)
else -> "unknown type".apply(::println)
}
}
fun getValue(): Any {
return 100F
}
我們可以嘗試把 kotlin 1.3 版本之后 when 表達(dá)式使用代碼反編譯成 Java 代碼:
public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
Object value = getValue();
String var2;
if (value instanceof Integer) {
var2 = "This is Int Type, value is " + value;
System.out.println(var2);
} else if (value instanceof String) {
var2 = "This is String Type, value is " + value;
System.out.println(var2);
} else if (value instanceof Double) {
var2 = "This is Double Type, value is " + value;
System.out.println(var2);
} else if (value instanceof Float) {
var2 = "This is Float Type, value is " + value;
System.out.println(var2);
} else {
var2 = "unknown type";
System.out.println(var2);
}
}
@NotNull
public static final Object getValue() {
return 100.0F;
}
通過對比發(fā)現(xiàn),Kotlin 1.3 前后 when 表達(dá)式的增強(qiáng),僅僅是把原來外部那一行代碼,縮進(jìn)到 when 里寫,然而兩次寫法反編譯的 Java 代碼是一致的。
4. 使用 when 表達(dá)式替代if表達(dá)式
和if
表達(dá)式一樣,when
表達(dá)式也是帶有返回值的。建議對于多層條件級或嵌套條件控制的使用建議使用when
替代if-else
:
fun eval(number: Number) {
if (number is Int) {
println("this is int number")
} else if (number is Double) {
println("this is double number")
} else if (number is Float) {
println("this is float number")
} else if (number is Long) {
println("this is long number")
} else if (number is Byte) {
println("this is byte number")
} else if (number is Short) {
println("this is Short number")
} else {
throw IllegalArgumentException("invalid argument")
}
}
//多層級條件使用when表達(dá)式
fun eval(number: Number): String = when (number) {
is Int -> "this is int number"
is Double -> "this is double number"
is Float -> "ths is float number"
is Long -> "this is long number"
is Byte -> "this is byte number"
is Short -> "this is Short number"
else -> "invalid number"
}
5. 小結(jié)
到這里 Kotlin 中的條件控制就闡述完畢了,可以發(fā)現(xiàn) Kotlin 中條件控制和 Java 還是存在著很多的不一樣的,需要多多練習(xí)多多理解,下一篇我們將進(jìn)入 Kotlin 中循環(huán)控制。