Any、Unit、Nothing
kotlin中有3个特殊的常用类型
- Any
- Unit
- Nothing
Any
/**
* The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass.
*/
public open class Any {}
Any是Kotlin中所有类的父类,类似Java中的Object
/**
* 分析Any
* @param any 不可null的Any
* @param any2 可以null的Any
* @return 返回值随意
*/
fun any1(any: Any, any2: Any?) : Any?{
return null
}
反编译
public final class AnyUnitNothingKt {
@Nullable
public static final Object any1(@NotNull Object any, @Nullable Object any2) {
Intrinsics.checkNotNullParameter(any, "any");
return null;
}
}
结论:
- Any确实反编译成了Object
- Any? 与 Object 更加类似,因为Object可以为null
Unit
/**
* The type with only one value: the `Unit` object. This type corresponds to the `void` type in Java.
*/
public object Unit {
override fun toString() = "kotlin.Unit"
}
Unit对标的是Java中的void,因为kotlin中万物皆对象,没有返回值也是一种对象,单例
fun unit1(u : Unit): Unit {}
反编译
public static final void unit1(@NotNull Unit u) {
Intrinsics.checkNotNullParameter(u, "u");
}
结论:
- Unit作为反编译后还是一个Unit对象
- Unit作为返回值,反编译后被修改为void
Nothing
/**
* Nothing has no instances. You can use Nothing to represent "a value that never exists": for example,
* if a function has the return type of Nothing, it means that it never returns (always throws an exception).
*/
public class Nothing private constructor()
非常特殊的一个类,构造函数私有,并且没有提供对象的方法,永远不可能存在具体对象
作用:
- 标记一个值永远不存在,不能实例化
- 作为返回值标记一个函数永远不可能有返回值
fun nothing1(): Nothing {
// 死循环,无法返回,可编译,不报错
while (true) { print(1)}
}
fun nothing2(): Nothing {
// 直接抛异常,可编译,不报错
throw RuntimeException()
}
// 不能返回,报错
/*fun nothing3(): Nothing {
return ""
}*/
不熟悉的关键字
关键字 | 说明 |
---|---|
internal | 当前module才能使用,不能跨module使用 |
JvmOverloads
自定义View相关构建,等待补充
companion object
伴生类,是一个单例,随着对象的加载自动创建,可以写在接口中。companion object [className]
是完整形态,是可以带有名字的,匿名的className = Companion,一个类中只能有一个伴生对象
带名字的伴生类:很少用到,corontine中Element的key就是这种具名伴生,保证了类与key的一一对应
class Companion1 {
// 伴生类无论是否带Class Name,都只能有一个,匿名的companion object,类名就是Companion
// companion object{} // 2个companion object报错
companion object Key1{
val myKey = "kkk"
}
}
匿名伴生类:常用
class Companion2 {
companion object{
val key2 ="2222"
}
}
�调用的类中带有伴生对象,会直接引用到伴生对象上
fun main() {
// 自动获取到伴生类对象
val companion1 = Companion1
val companion4 = Companion1.Key1
println(companion1 === companion4) // 打印true,就是同一个对象
// 自动从伴生类中拿变量,下面2个等价
Companion1.myKey
Companion1.Key1.myKey
// 匿名的伴生类,类名就是Companion,下面2个等价
val companion2 = Companion2.key2
val companion3 = Companion2.Companion.key2
}