1、新建kt并运行
- 新建文件kt


- 运行文件kt

2、kotlin语句 if when的使用
var x = 5
val y = 9
if (x in 1..8) {
println("x 在区间内")
}
说明:
var:定义变量 val定义常量。

代码中会看到那个<=,也就是说包括1,8。
3、输出

4、所有代码,可以测试:
fun main(args: Array<String>) {
var x = 5
val y = 9
if (x in 1..8) {
println("x 在区间内")
}
x = 0
when (x) {
0, 1 -> println("x == 0 or x == 1")
else -> println("otherwise")
}
when (x) {
1 -> println("x == 1")
2 -> println("x == 2")
else -> { // 注意这个块
println("x 不是 1 ,也不是 2")
}
}
when (x) {
in 0..10 -> println("x 在该区间范围内")
else -> println("x 不在该区间范围内")
}
val validNumbers= arrayListOf(1,2)
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
val items = setOf("apple", "banana", "kiwi")
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
println(hasPrefix("prefix_9023"))
}
fun hasPrefix(x: Any) = when(x) {
is String -> x.startsWith("prefix")
else -> false
}
5、kotlin语法并不难,与swift也有相似之处,目的都是为了开发简化。