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

Top-level functions

In addition to member functions and local functions, Kotlin also supports declaring top-level functions. These are functions that exist outside of any class, object, or interface and are defined directly inside a file. The name "top-level" comes from the fact that functions are not nested inside any structure and so they are at the top of the hierarchy of classes and functions.

Top-level functions are especially useful for defining helper or utility functions. It does not necessarily make sense to group them with other functions or create them when the contained object adds no value. In Java, these kinds of functions exist as static functions inside the helper classes. An example would be the functions of collections in the Java standard library.

However, some functions are so standalone that it makes little sense to take the trouble of creating a containing object. A good example would be require. This is a Kotlin standard library function that is used to ensure that parameters, when invoked, satisfy the invariant conditions. For example, if a parameter should always be greater than 10, we can write the following:

    fun foo(k: Int) { 
      require(k > 10, { "k should be greater than 10" }) 
    } 

This function and its siblings, namely check, error, and requireNotNull, could be placed inside an object called assertions (or another name that means the same), but this adds no value, and, by using top-level functions, we could define these functions directly in a file called assertions.kt.

主站蜘蛛池模板: 乌拉特后旗| 宁阳县| 宜兰市| 弋阳县| 东乡族自治县| 张家川| 工布江达县| 昌都县| 光泽县| 秦安县| 绥化市| 海南省| 五寨县| 永顺县| 通州区| 南昌市| 金阳县| 磐安县| 武山县| 灵武市| 南平市| 诏安县| 郓城县| 炎陵县| 察雅县| 蒙自县| 读书| 东光县| 锡林郭勒盟| 南汇区| 武平县| 沈阳市| 凉城县| 天祝| 阿拉善右旗| 潞城市| 衡水市| 拉萨市| 庆城县| 天全县| 长丰县|