Any、Unit、Nothing

kotlin中有3个特殊的常用类型

  1. Any
  2. Unit
  3. Nothing

Any

  1. /**
  2. * The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass.
  3. */
  4. public open class Any {}

Any是Kotlin中所有类的父类,类似Java中的Object

  1. /**
  2. * 分析Any
  3. * @param any 不可null的Any
  4. * @param any2 可以null的Any
  5. * @return 返回值随意
  6. */
  7. fun any1(any: Any, any2: Any?) : Any?{
  8. return null
  9. }

反编译

  1. public final class AnyUnitNothingKt {
  2. @Nullable
  3. public static final Object any1(@NotNull Object any, @Nullable Object any2) {
  4. Intrinsics.checkNotNullParameter(any, "any");
  5. return null;
  6. }
  7. }

结论:

  1. Any确实反编译成了Object
  2. Any? 与 Object 更加类似,因为Object可以为null

Unit

  1. /**
  2. * The type with only one value: the `Unit` object. This type corresponds to the `void` type in Java.
  3. */
  4. public object Unit {
  5. override fun toString() = "kotlin.Unit"
  6. }

Unit对标的是Java中的void,因为kotlin中万物皆对象,没有返回值也是一种对象,单例

  1. fun unit1(u : Unit): Unit {}

反编译

  1. public static final void unit1(@NotNull Unit u) {
  2. Intrinsics.checkNotNullParameter(u, "u");
  3. }

结论:

  1. Unit作为反编译后还是一个Unit对象
  2. Unit作为返回值,反编译后被修改为void

Nothing

  1. /**
  2. * Nothing has no instances. You can use Nothing to represent "a value that never exists": for example,
  3. * if a function has the return type of Nothing, it means that it never returns (always throws an exception).
  4. */
  5. public class Nothing private constructor()

非常特殊的一个类,构造函数私有,并且没有提供对象的方法,永远不可能存在具体对象

作用:

  1. 标记一个值永远不存在,不能实例化
  2. 作为返回值标记一个函数永远不可能有返回值
  1. fun nothing1(): Nothing {
  2. // 死循环,无法返回,可编译,不报错
  3. while (true) { print(1)}
  4. }
  5. fun nothing2(): Nothing {
  6. // 直接抛异常,可编译,不报错
  7. throw RuntimeException()
  8. }
  9. // 不能返回,报错
  10. /*fun nothing3(): Nothing {
  11. return ""
  12. }*/

不熟悉的关键字

关键字 说明
internal 当前module才能使用,不能跨module使用

JvmOverloads

自定义View相关构建,等待补充

companion object

伴生类,是一个单例,随着对象的加载自动创建,可以写在接口中。
companion object [className]是完整形态,是可以带有名字的,匿名的className = Companion,一个类中只能有一个伴生对象
带名字的伴生类:很少用到,corontine中Element的key就是这种具名伴生,保证了类与key的一一对应

  1. class Companion1 {
  2. // 伴生类无论是否带Class Name,都只能有一个,匿名的companion object,类名就是Companion
  3. // companion object{} // 2个companion object报错
  4. companion object Key1{
  5. val myKey = "kkk"
  6. }
  7. }

匿名伴生类:常用

  1. class Companion2 {
  2. companion object{
  3. val key2 ="2222"
  4. }
  5. }

�调用的类中带有伴生对象,会直接引用到伴生对象上

  1. fun main() {
  2. // 自动获取到伴生类对象
  3. val companion1 = Companion1
  4. val companion4 = Companion1.Key1
  5. println(companion1 === companion4) // 打印true,就是同一个对象
  6. // 自动从伴生类中拿变量,下面2个等价
  7. Companion1.myKey
  8. Companion1.Key1.myKey
  9. // 匿名的伴生类,类名就是Companion,下面2个等价
  10. val companion2 = Companion2.key2
  11. val companion3 = Companion2.Companion.key2
  12. }