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

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.
主站蜘蛛池模板: 平定县| 岚皋县| 新巴尔虎左旗| 库伦旗| 枣强县| 正定县| 米泉市| 景泰县| 噶尔县| 石棉县| 光泽县| 盖州市| 大关县| 炎陵县| 五大连池市| 乐清市| 修武县| 商南县| 洮南市| 枝江市| 科尔| 合肥市| 太谷县| 忻城县| 博罗县| 扶风县| 林甸县| 渝中区| 海城市| 宁津县| 屏东市| 峨眉山市| 内丘县| 闻喜县| 哈密市| 阿拉善左旗| 滁州市| 汉川市| 十堰市| 冷水江市| 自治县|