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

Control flow as expressions

An expression is a statement that evaluates to a value. The following expression evaluates to true:

    "hello".startsWith("h")  

A statement, on the other hand, has no resulting value returned. The following is a statement because it assigns a value to a variable, but does not evaluate to anything itself:

    val a = 1

In Java, the common control flow blocks, such as if...else and try..catch, are statements. They do not evaluate to a value, so it is common in Java, when using these, to assign the results to a variable initialized outside the block:

    public boolean isZero(int x) { 
      boolean isZero; 
      if (x == 0) 
        isZero = true; 
      else 
        isZero = false; 
      return isZero; 
    }

In Kotlin, the if...else and try..catch control flow blocks are expressions. This means the result can be directly assigned to a value, returned from a function, or passed as an argument to another function.

This small, yet powerful, feature allows boilerplate code to be reduced, code made more readable, and the use of mutable variables avoided. The typical use case of declaring a variable outside of an if statement to then initialize it inside either branch can be avoided completely:

    val date = Date() 
    val today = if (date.year == 2016) true else false 
 
    fun isZero(x: Int): Boolean { 
      return if (x == 0) true else false 
    } 

A similar technique can be used for the try..catch blocks, as follows:

    val success = try { 
      readFile() 
      true 
    } catch (e: IOException) { 
      false 
    } 

In the preceding example, the success variable will contain the result of the try block only if it completes successfully; otherwise, the catch clause return value will be used, in this case, false.

Expressions need not be single lines. They can be blocks, and in those cases, the last line must be an expression, and that expression is the value that the block evaluates to.

When using if as an expression, you must include the else clause. Otherwise, the compiler will not know what to do if if did not evaluate to true. If you do not include the else clause, the compiler will display a compile-time error.
主站蜘蛛池模板: 麟游县| 株洲市| 娄底市| 辽源市| 平顺县| 乌恰县| 岳阳市| 金昌市| 札达县| 黑龙江省| 石景山区| 琼海市| 商都县| 潮州市| 乡宁县| 射洪县| 长兴县| 巴塘县| 翁牛特旗| 镇远县| 浮山县| 方山县| 咸阳市| 遵义市| 灵台县| 葵青区| 兴化市| 祥云县| 玉门市| 大姚县| 大英县| 长武县| 尖扎县| 德令哈市| 大宁县| 东台市| 漠河县| 临西县| 东光县| 门头沟区| 青川县|