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

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.
主站蜘蛛池模板: 马公市| 满洲里市| 喀喇| 五莲县| 濮阳市| 光泽县| 应城市| 新津县| 浦东新区| 恩施市| 茌平县| 南平市| 中山市| 昭苏县| 托克逊县| 彝良县| 双辽市| 神农架林区| 大邑县| 措勤县| 城步| 富蕴县| 凤冈县| 右玉县| 来宾市| 郴州市| 涪陵区| 淄博市| 永和县| 泾源县| 青州市| 永顺县| 留坝县| 洪湖市| 和政县| 武邑县| 怀宁县| 叙永县| 高陵县| 聂拉木县| 霍山县|