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

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.
主站蜘蛛池模板: 苏州市| 宜丰县| 原阳县| 汉阴县| 轮台县| 西盟| 儋州市| 彭泽县| 翼城县| 威信县| 南阳市| 昌吉市| 遂平县| 崇礼县| 武威市| 丽水市| 井研县| 济源市| 长寿区| 普兰店市| 攀枝花市| 黄浦区| 保山市| 迁安市| 古田县| 龙陵县| 礼泉县| 徐州市| 堆龙德庆县| 成武县| 额尔古纳市| 耒阳市| 惠水县| 亚东县| 红桥区| 柳林县| 大同县| 怀仁县| 西青区| 加查县| 仁布县|