Kotlin 的扩展函数是如何工作的?

Use*_*291 1 scala compilation implicit kotlin kotlin-extension

假设我想要一个提供square方法的整数。

科特林

fun Int.square() = this * this
Run Code Online (Sandbox Code Playgroud)

用法:

println("${20.square()}")
Run Code Online (Sandbox Code Playgroud)

文档:

扩展实际上并不修改它们扩展的类。通过定义扩展,您不会将新成员插入到类中,而只是使新函数可以使用这种类型的变量上的点符号调用。

我们要强调的是,扩展函数是静态调度的

我的期望是他们在编译期间只是将它添加到扩展类的成员函数中,但这是他们明确否认的,所以我的下一个想法是它可能“有点”像 scala 隐式。

斯卡拉

object IntExtensions{
    implicit Class SquareableInt(i:Int){
        def square = i*i
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

import IntExtensions._
Run Code Online (Sandbox Code Playgroud)

进而

println(f"${20.square}")
Run Code Online (Sandbox Code Playgroud)

文档:

隐式类被脱糖为类和隐式方法配对,其中 implciit 方法模仿类的构造函数。

生成的隐式方法将与隐式类同名。

但是 scala 隐式创建了一个新类,这将禁用this.

那么...... Kotlin 是如何扩展类的呢?“使可调用”并没有告诉我太多。

小智 6

在您的情况下,Kotlin 只需创建名为“filename”Kt 的简单实用程序类和静态方法“ int square(int x) ”(java 伪代码)

从Java它看起来像这样

// filename int-utils.kt
final class IntUtilsKt {
    public static int square(int x) {
        return x * x;
    }
}
Run Code Online (Sandbox Code Playgroud)

在这一切之后,

val 结果 = 20.square()

将被转换(在字节码级别)为

val 结果 = IntUtilsKt.square(20);

PS 您可以使用 IDEA 操作“Show Kotlin byte-code”自行查看