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

Single expression functions

Usually, a function must declare its return type; an exception exists only for functions that consist of a single expression. These are often referred to as one line or single line functions. Such functions can use a shortened syntax that omits the braces and uses the = symbol before the expression rather than the return keyword:

    fun square(k: Int) = k * k 

You can see how the function does not need to declare the return value of Int. This is inferred by the compiler. The rationale behind this feature is that very short functions are easy to read, and the return value is a bit of extra noise that doesn't add much to the overall process. However, you can always include the return value if you think that it makes things clearer:

    fun square2(k: Int): Int = k * k 

Single expression functions can always be written in the regular style if desired. For example, the following two functions are identical and are compiled to the same bytecode:

    fun concat1(a: String, b: String) = a + b 
    fun concat2(a: String, b: String): String { 
      return a + b 
    } 
The compiler enforces the rule that only a single expression function can omit the return type.
主站蜘蛛池模板: 柳江县| 进贤县| 吴堡县| 湛江市| 额尔古纳市| 文化| 吕梁市| 神池县| 徐水县| 光山县| 新乐市| 满洲里市| 池州市| 益阳市| 昭苏县| 华阴市| 神农架林区| 南投县| 青河县| 常熟市| 富锦市| 壶关县| 安义县| 洛南县| 英德市| 彰化县| 赤壁市| 韶山市| 安丘市| 慈溪市| 镇原县| 新疆| 张家界市| 通渭县| 岑巩县| 阜新| 莱州市| 辽宁省| 新竹县| 满城县| 南溪县|