Kotlin 如何更有效地使用if条件?

Kotlin 如何更有效地使用if条件?,kotlin,if-statement,Kotlin,If Statement,我对编程有一点了解,但我对下面的if语句有疑问 val age = 21 if(age >= 21) { println("You can drink now") } else if(age >= 18) { println("You can vote now") } else if(age >= 16) { println("You can drive now") } else{ prin

我对编程有一点了解,但我对下面的if语句有疑问

val age = 21
if(age >= 21) {
    println("You can drink now")
} else if(age >= 18) {
    println("You can vote now")
} else if(age >= 16) {
   println("You can drive now")
} else{
   println("You are too young")
}
在上面的if语句中,所有条件都为true,但我知道只会执行第一个条件。如果我想检查所有条件是否为真,我可以对所有条件使用单独的If条件。有没有办法以更有效的方式实现这一点。请分享你的知识。提前感谢。

似乎java
开关
语句的功能可以让您了解所有情况(除非使用了
中断

我认为这在kotlin看起来相当不错:

    if (age >= 21) println("You can drink now")
    if (age >= 18) println("You can vote now")
    if (age >= 16) println("You can drive now")
    if (age < 16) println("You are too young")

如果(年龄>=21)println(“你现在可以喝酒了”)
如果(年龄>=18)println(“您现在可以投票”)
如果(年龄>=16)println(“您现在可以开车了”)
如果(年龄<16岁)println(“你太年轻了”)
以功能方式:

val age = 21

listOf<Pair<(Int) -> Boolean, () -> Unit>>(
        { i:Int -> i >= 21 } to { println("You can drink now") },
        { i:Int -> i >= 18 } to { println("You can vote now") },
        { i:Int -> i >= 16 } to { println("You can drive now") },
        { i:Int -> i <  16 } to { println("You are too young") }
).forEach { (check, action) ->
    if (check.invoke(age)) {
        action.invoke()
    }
}
val年龄=21岁
单元列表>>(
{i:Int->i>=21}到{println(“你现在可以喝酒了”)},
{i:Int->i>=18}到{println(“你现在可以投票了”)},
{i:Int->i>=16}到{println(“你现在可以开车了”)},
{i:Int->i<16}到{println(“你太年轻了”)}
).forEach{(检查、操作)->
if(检查调用(年龄)){
action.invoke()
}
}

如果某个条件只有在另一个条件为真时才为真,则可以嵌套它们以避免在更一般的条件为假时进行冗余检查:

if(年龄>=16岁){
如果(年龄>=18){//如果年龄<16,则不会执行
如果(年龄>=21){//如果年龄<18,则不会执行
println(“你现在可以喝酒了”)
}
println(“你现在可以投票了”)
}
println(“你现在可以开车了”)
}否则{
println(“你太年轻了”)
}
它的效率略高,但可读性远不如简单:

如果(年龄>=21)println(“你现在可以喝酒了”)
如果(年龄>=18)println(“您现在可以投票”)
如果(年龄>=16)println(“您现在可以开车了”)
如果(年龄<16岁)println(“你太年轻了”)

因此,如果条件检查很便宜,并且/或者在您的情况下性能不是绝对优先的,我会选择后一种变体。

一个简单问题的简单解决方案。这里不需要复杂性。Kotlin没有
开关,因为它不需要它。当
@Alex.T java的开关和kotlin的行为不同时,它有开关<代码>开关将执行所有为真的表达式,而
when
将在第一个表达式为真时停止。OP希望执行所有正确的语句