IP地址检测
视频播放器
输入关键词搜索
登录
Kotlin扩展函数/扩展属性

Kotlin扩展函数/扩展属性

2024-06-30
编程开发

扩展函数

顶层(Top-Level)扩展函数

// 文件名 Test.kt
fun String.extendedFun(i: Int): String {
    // this代表(.)前面的对象,在这里,就是String对象
    return this + i
}

反编译结果

public final class TestKt {
   @NotNull
   public static final String extendedFun(@NotNull String $this$extendedFun, int i) {
      return $this$extendedFun + i;
   }
}

可以看到,顶层的扩展函数被编译成了static静态函数,因此这个扩展函数在任何地方都可以被调用。当我们调用"hello".extendedFun(123)的时候,其实就是在调用TestKt.extendedFun("hello",123)。这里就不贴反编译的代码了,可以自己试一试

成员-扩展函数

写在类里面的扩展函数,比如:

class Test {
    fun String.extendedFun(i: Int): String {
        return this + i
    }
}

反编译结果

public final class Test {
   @NotNull
   public final String extendedFun(@NotNull String $this$extendedFun, int i) {
      Intrinsics.checkNotNullParameter($this$extendedFun, "$this$extendedFun");
      return $this$extendedFun + i;
   }
}

只能在 「当前类」 或者 「当前类的子类」 里面被调用,避免扩展函数污染。比如:

class Test {
    fun String.extendedFun(i: Int): String {
        return this + i
    }
    
    fun example(){
        "HelloWorld".extendedFun(123) // 可以调用
    }
}

"HelloWorld".extendedFun(123) // 在类外面调用,会报错

扩展属性

顶层(Top-Level)扩展属性

val String.extendedProperty: String
    get() = "Hello Kotlin"

反编译结果

public final class TestKt {
   @NotNull
   public static final String getExtendedProperty(@NotNull String $this$extendedProperty) {
      return "Hello Kotlin";
   }
}

扩展属性被封装成静态的getXxx()方法,任何地方都可以调用

成员-扩展属性

写在类里面的扩展属性

class Test {
    val String.extendedProperty: String
        get() = "Hello Kotlin"
}

反编译结果

public final class Test {
   @NotNull
   public final String getExtendedProperty(@NotNull String $this$extendedProperty) {
      return "Hello Kotlin";
   }
}

只能在 「当前类」 或者 「当前类的子类」 里面被调用

class Test {
    val String.extendedProperty: String
        get() = "Hello Kotlin"

    fun example() {
        "example".extendedProperty
    }
}

"example".extendedProperty // 不在类里面,调用时会报错

结论

  • 顶层扩展函数(或属性)会被编译成static类型的函数(或属性),可以在任何地方调用
  • 成员扩展函数(或属性)被编译成非static类型的函数(或属性),只能在 「当前类」 或者 「当前类的子类」 里面被调用
THE END
0/500
暂无评论
📢网站公告
欢迎来到这里
⚙️实用工具
html转pdfmarkdown编辑器
本站推荐:腾讯云服务器仅需2.3折 (点击直达)
用户协议
隐私政策
Build Time: 2025-02-06 16:15:33