Kotlin 的扩展函数是如何工作的?
How do Kotlin's extension functions work?
假设我想要一个提供 square
方法的整数。
Kotlin:
fun Int.square() = this * this
用法:
println("${20.square()}")
文档:
Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.
We would like to emphasize that extension functions are dispatched statically
我的期望是他们只是在编译期间将它添加到扩展 class 的成员函数中,但这是他们明确否认的,所以我的下一个想法是它可能是“有点像" 就像 scala 隐含的。
Scala:
object IntExtensions{
implicit Class SquareableInt(i:Int){
def square = i*i
}
}
用法:
import IntExtensions._
然后
println(f"${20.square}")
文档:
An implicit class is desugared into a class and implicit method pairing, where the implciit method mimics the constructor of the class.
The generated implicit method will have the same name as the implicit class.
但是 scala 隐式创建一个新的 class,这将禁用 this
.
那么……Kotlin 是如何扩展 classes 的? “使可调用”并没有告诉我太多。
在您的情况下,Kotlin 只需创建名称为 "filename"Kt 的简单实用程序-class 和静态方法“int square(int x)" (java伪代码)
从 Java 看起来像这样
// filename int-utils.kt
final class IntUtilsKt {
public static int square(int x) {
return x * x;
}
}
然后所有调用
val result = 20.square()
将(在字节码级别)转换为
val result = IntUtilsKt.square(20);
P.S。
大家可以自己用IDEA动作看看"Show Kotlin byte-code"
假设我想要一个提供 square
方法的整数。
Kotlin:
fun Int.square() = this * this
用法:
println("${20.square()}")
文档:
Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.
We would like to emphasize that extension functions are dispatched statically
我的期望是他们只是在编译期间将它添加到扩展 class 的成员函数中,但这是他们明确否认的,所以我的下一个想法是它可能是“有点像" 就像 scala 隐含的。
Scala:
object IntExtensions{
implicit Class SquareableInt(i:Int){
def square = i*i
}
}
用法:
import IntExtensions._
然后
println(f"${20.square}")
文档:
An implicit class is desugared into a class and implicit method pairing, where the implciit method mimics the constructor of the class.
The generated implicit method will have the same name as the implicit class.
但是 scala 隐式创建一个新的 class,这将禁用 this
.
那么……Kotlin 是如何扩展 classes 的? “使可调用”并没有告诉我太多。
在您的情况下,Kotlin 只需创建名称为 "filename"Kt 的简单实用程序-class 和静态方法“int square(int x)" (java伪代码)
从 Java 看起来像这样
// filename int-utils.kt
final class IntUtilsKt {
public static int square(int x) {
return x * x;
}
}
然后所有调用
val result = 20.square()
将(在字节码级别)转换为
val result = IntUtilsKt.square(20);
P.S。 大家可以自己用IDEA动作看看"Show Kotlin byte-code"