- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 248字
- 2021-06-24 14:13:36
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.
- 新編Visual Basic程序設(shè)計上機(jī)實驗教程
- 從零構(gòu)建知識圖譜:技術(shù)、方法與案例
- 數(shù)據(jù)庫程序員面試筆試真題與解析
- SoapUI Cookbook
- Java高手真經(jīng)(高級編程卷):Java Web高級開發(fā)技術(shù)
- 實用防銹油配方與制備200例
- Java開發(fā)入行真功夫
- R語言編程指南
- Java程序設(shè)計與實踐教程(第2版)
- C語言程序設(shè)計實踐教程
- Troubleshooting PostgreSQL
- Nexus規(guī)模化Scrum框架
- Hands-On Robotics Programming with C++
- SEO教程:搜索引擎優(yōu)化入門與進(jìn)階(第3版)
- 青少年P(guān)ython趣味編程