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

Type hierarchy

In Kotlin, the uppermost type is called Any. This is analogous to Java's object type. The Any type defines the well-known toString, hashCode, and equals methods. It also defines the extension methods apply, let, and to, among others. These methods will be described in more detail in Chapter 5, Higher-Order Functions and Functional Programming.

The Unit type is the equivalent of a void in Java. Having a Unit type is common in a functional programming language, and the distinction between void and Unit is subtle. Void is not a type, but a special edge case that is used to indicate to the compiler that a function returns no value. Unit is a proper type, with a singleton instance, also referred to as Unit or (). When a function is defined as a returning Unit, then it will return the singleton unit instance.

This results in greater soundness of the system type as now all functions can be defined as having a return value, even if it's just the Unit type, and functions that have no arguments can be defined as accepting the Unit type.

Where Kotlin differs from Java most notably is in the addition of a bottom type, Nothing, which is a type that has no instances. Similar to how Any is a superclass of all types, Nothing is the subclass of all types. For those who are new to the concept of a bottom type, it might seem strange to have such a type, but it has several use cases.

First, Nothing can be used to inform the compiler that a function never completes normally; for example, it might loop forever, or always throw an exception. Another example is empty immutable collections. An empty list of Nothing could be assigned to a variable accepting a list of strings. Since the list is empty, we cannot retrieve any values from it, and therefore Nothing is fine to use as the generic parameter. Therefore, these empty values can be cached and reused. This is actually the basis of the implementation of the standard library functions emptyList(), emptySet(), and so on.

主站蜘蛛池模板: 宝清县| 沭阳县| 夹江县| 宁陕县| 余庆县| 宜君县| 孟津县| 甘南县| 合阳县| 桐乡市| 赞皇县| 乐安县| 定兴县| 兴宁市| 曲松县| 开封县| 南充市| 凤庆县| 额尔古纳市| 汽车| 蚌埠市| 始兴县| 保山市| 左权县| 当阳市| 阳西县| 庆城县| 阿勒泰市| 瑞昌市| 石河子市| 睢宁县| 灌南县| 区。| 久治县| 赤城县| 保定市| 永和县| 洪洞县| 通渭县| 赤壁市| 嵊州市|