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

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.
主站蜘蛛池模板: 尤溪县| 武山县| 太原市| 石门县| 南昌市| 安塞县| 厦门市| 和田市| 襄樊市| 怀远县| 镇安县| 故城县| 枝江市| 新竹市| 涪陵区| 长子县| 宿松县| 聂拉木县| 自贡市| 万山特区| 金华市| 德昌县| 裕民县| 绩溪县| 金寨县| 南陵县| 北宁市| 九江市| 华池县| 闻喜县| 濉溪县| 兰西县| 鸡东县| 任丘市| 浦东新区| 额尔古纳市| 遂川县| 阜新市| 无锡市| 昌宁县| 宜丰县|