Kotlin 条件控制学习笔记
条件控制是编程语言中常用的一种结构,可以根据条件的不同执行不同的代码块。在 Kotlin 中,条件控制包含 if 表达式、when 表达式和 try 表达式等。
if 表达式
if 表达式用于判断一个表达式的值是否为真,如果为真则执行特定代码块,否则执行另一个代码块。语法如下:
Copy Codeif (condition) {
// code block to be executed if condition is true
} else {
// code block to be executed if condition is false
}
例如:
kotlinCopy Codeval x = 2
if (x > 1) {
println("x is greater than 1")
} else {
println("x is less than or equal to 1")
}
输出结果为:
Copy Codex is greater than 1
when 表达式
when 表达式用于根据给定的条件执行不同的代码块。它类似于 switch 语句,但更加强大。语法如下:
Copy Codewhen (x) {
value1 -> {
// code block to be executed if x is equal to value1
}
value2 -> {
// code block to be executed if x is equal to value2
}
...
else -> {
// code block to be executed if none of the above conditions are met
}
}
例如:
kotlinCopy Codeval x = 2
when (x) {
1 -> println("x equals 1")
2 -> println("x equals 2")
else -> println("x does not equal 1 or 2")
}
输出结果为:
Copy Codex equals 2
try 表达式
try 表达式用于捕获异常并执行特定代码块。语法如下:
Copy Codetry {
// code block that may throw an exception
} catch (e: Exception) {
// code block to be executed if an exception is thrown
} finally {
// optional code block to be executed regardless of whether an exception is thrown
}
例如:
kotlinCopy Codefun divide(x: Int, y: Int): Int {
return try {
x / y
} catch (e: Exception) {
-1
}
}
println(divide(10, 2)) // output: 5
println(divide(10, 0)) // output: -1
以上就是 Kotlin 条件控制的基本知识,希望本文能对你有所帮助。