網站首頁 編程語言 正文
Tips:Kotlin 中沒有 switch-case。
一、if表達式
1、帶返回值if表達式
在 Kotlin 中,if 是一個表達式所以它會返回一個值,表達式的值為表達式作 用域內最后一行的值。這一點和 Java 是不同的, 在 Java 中 if 僅僅是語句。
//一般類似 java 中傳統 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))
}
//作為表達式則可以這樣
fun maxOf(a: Int, b: Int):Int{
return if (a > b) a else b
}
fun main(args: Array<String>) {
println(maxOf(1, 5))
}
if 表達式分支可以是代碼塊,也可以把作用域內最后一行表達式的值作為該 分支塊的值:
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))
}
2、if 表達式替代三目運算符
因為在 Kotlin 中 if 表達式是帶有返回值的,所以在 Kotlin 中是不需要三目 運算符(xxx ? xxx : xxx), 因為 if 表達式這些都能做到。
//Java 中三目運算符
public int maxOf(int a, int b) {
return a > b ? a : b;
}
而在 Kotlin 中則可以直接使用 if 表達式來使用:
//Kotlin 中的 if 表達式
fun maxOf(a: Int, b: Int) = if (a > b) a else b
Tips:如果你使用 if 作為表達式而不是語句(例如:返回它的值或者把它賦 給變量),該表達式需要有 else 分支。
3、多級if表達式
和 Java 一樣 Kotlin 也支持 if-else if-else 等多級條件選擇,但是一般如 果這種帶多級條件選擇的 IDE 會提示你使用 when 表達式來替代: 下面這個案例會使用 if-else if-else 來判斷變量 number 是何種數據類型:
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 函數需要有返回值的時候,必須要有 else 分支。
二、When表達式
在 Kotlin 中使用 when 表達式替代了類似 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 將它的參數與所有的分支條件順序比較,直到某個分支滿足條 件。 when 既可以被當做表達式使用也可以被當做語句使用。如果它被當做 表達式, 符合條件的分支的值就是整個表達式的值,如果當做語句使用, 則忽略個別分支的值。(像 if 一樣,每一個分支可以是一個代碼塊,它的值 是塊中最后的表達式的值。)
Tips:如果其他分支都不滿足條件將會求值 else 分支。 如果 when 作為一 個表達式使用,則必須有 else 分支, 除非編譯器能夠檢測出所有的可能情 況都已經覆蓋了。
如果很多分支需要用相同的方式處理,則可以把多個分支條件放在一起,用 逗號分隔:
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 鏈。 如果不提供參數,所有的分支條件都是 簡單的布爾表達式,而當一個分支的條件為真時則執行該分支:
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")
}
}
三、when 表達式的功能增強
自從 Kotlin1.3 版本后對 when 表達式做了一個寫法上的優化,為什么這么 說呢? 僅僅就是寫法上的優化,實際上什么都沒做. 它主要是解決什么問題 呢?細心的小伙伴會發現,在 Kotlin 1.3 版本之前 when 表達式內部是不能使 用傳入的值的。
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 表達式使用代碼反編譯成 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;
}
2、Kotlin 1.3 版本之后 when
fun main(args: Array<String>) {
when (val value = getValue()) {//when 表達式條件直接是一個表達式,并用
value 保存了返回值, 實際上相當于把外部那一行縮進來寫
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 表達式的增強,僅僅是把原來外部那一行代碼,縮 進到 when 里寫,然而兩次寫法反編譯的 Java 代碼是一致的。
四、使用 when 表達式替代 if 表達式
和 if 表達式一樣,when 表達式也是帶有返回值的。建議對于多層條件級或嵌 套條件控制的使用建議使用 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 表達式
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"
}
總結
到這里 Kotlin 中的條件控制就闡述完畢了,可以發現 Kotlin 中條件控制和 Java 還是存在著很多的不一樣的,需要多多練習多多理解,下一篇我們將進 入 Kotlin 中循環控制。
原文鏈接:https://blog.csdn.net/m0_58941767/article/details/126843813
相關推薦
- 2022-11-06 react中關于Context/Provider/Consumer傳參的使用_React
- 2022-03-07 Centos7環境下YUM的搭建方法_Linux
- 2022-09-25 Linux系統CentOS的本地host查詢
- 2022-10-12 Python?Pandas的concat合并_python
- 2022-10-18 C#模擬實現鼠標自動點擊與消息發送功能_C#教程
- 2022-06-06 Rust字符串字面值的一些經驗總結_相關技巧
- 2023-01-17 MATLAB算法技巧和實現斐波那契數列的解決思路_C 語言
- 2022-05-12 linq中的串聯操作符_實用技巧
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支