官术网_书友最值得收藏!

The if statement

At its core, Kotlin's if clause works the same way as in Java:

    val x = 5 
 
    if(x > 10){ 
        println("greater") 
    } else { 
        println("smaller") 
    } 

The version with the block body is also correct if the block contains single statements or expressions:

    val x = 5 
 
    if(x > 10) 
        println("greater") 
    else 
        println("smaller") 

Java, however, treats if as a statement while Kotlin treats if as an expression. This is the main difference, and this fact allows us to use more concise syntax. We can, for example, pass the result of an if expression directly as a function argument:

    println(if(x > 10) "greater" else "smaller") 

We can compress our code into single line, because the result of the if expression (of type String) is evaluated and then passed to the println method. When the condition x > 10 is true, then the first branch (greater) will be returned by this expression; otherwise, the second branch (smaller) will be returned by this expression. Let's examine another example:

 
    val hour = 10 
    val greeting: String 
    if (hour < 18) { 
        greeting = "Good day" 
    } else { 
        greeting = "Good evening" 
    } 

In the preceding example, we are using if as a statement. But as we know, if in Kotlin is an expression and the result of the expression can be assigned to a variable. This way we can assign the result of the if expression to a greeting variable directly:

    val greeting = if (hour < 18) "Good day" else "Good evening" 

But sometimes there is a need to place some other code inside the branch of the if statement. We can still use if as an expression. Then, the last line of the matching if branch will be returned as a result:

    val hour = 10 
     
    val greeting = if (hour < 18) { 
        //some code 
        "Good day" 
    } else { 
        //some code 
        "Good evening" 
    } 
 
    println(greeting) // Prints: "Good day" 

If we are using if as an expression rather than a statement, the expression is required to have an else branch. The Kotlin version is even better than Java. Since the greeting variable is defined as non-nullable, the compiler will validate the whole if expression and it will check that all cases are covered with branch conditions. Since if is an expression, we can use it inside a string template:

val age = 18 
val message = "You are ${ if (age < 18) "young" else "of age" } person" 
println(message) // Prints: You are of age person 

Treating if as an expression gives us a wide range of possibilities previously unavailable in the Java world.

主站蜘蛛池模板: 朔州市| 徐州市| 安庆市| 夏邑县| 仙游县| 安新县| 利川市| 安丘市| 自贡市| 襄城县| 泾源县| 长岛县| 富顺县| 柏乡县| 仙桃市| 太仆寺旗| 望谟县| 宣城市| 和政县| 尖扎县| 安庆市| 滁州市| 渝北区| 寿光市| 防城港市| 英吉沙县| 和硕县| 龙里县| 平武县| 万源市| 蕲春县| 剑河县| 舟山市| 丹阳市| 黔西| 兴仁县| 荆门市| 林州市| 阳朔县| 平潭县| 庆阳市|