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

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.

主站蜘蛛池模板: 沁水县| 满城县| 绍兴市| 农安县| 凤城市| 武汉市| 盖州市| 长乐市| 兰考县| 金川县| 吴堡县| 伊宁市| 鸡东县| 建昌县| 英德市| 哈尔滨市| 南通市| 监利县| 古丈县| 湖北省| 乐亭县| 淮北市| 永清县| 阳信县| 凭祥市| 长岛县| 鄢陵县| 建昌县| 陵水| 固原市| 冕宁县| 海林市| 宁夏| 桑日县| 郸城县| 凤山市| 阜阳市| 青川县| 连州市| 东明县| 罗山县|