- 简单代码
package kotlinTest.extensionmethod
class ExtensionMethodTest {
}
fun String.abc() {
println("abc")
}
fun main() {
"a".abc()
}
- 用as 反编译成java 代码之后的结果
// ExtensionMethodTest.java
package kotlinTest.extensionmethod;
import kotlin.Metadata;
@Metadata(
mv = {1, 6, 0},
k = 1,
xi = 2,
d1 = {"\u0000\f\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\u0018\u00002\u00020\u0001B\u0005¢\u0006\u0002\u0010\u0002¨\u0006\u0003"},
d2 = {"LkotlinTest/extensionmethod/ExtensionMethodTest;", "", "()V", "com.free.learn.main"}
)
public final class ExtensionMethodTest {
}
// ExtensionMethodTestKt.java
package kotlinTest.extensionmethod;
import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
@Metadata(
mv = {1, 6, 0},
k = 2,
xi = 2,
d1 = {"\u0000\u000e\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0010\u000e\n\u0000\u001a\u0006\u0010\u0000\u001a\u00020\u0001\u001a\n\u0010\u0002\u001a\u00020\u0001*\u00020\u0003¨\u0006\u0004"},
d2 = {"main", "", "abc", "", "com.free.learn.main"}
)
public final class ExtensionMethodTestKt {
public static final void abc(@NotNull String $this$abc) {
Intrinsics.checkNotNullParameter($this$abc, "$this$abc");
String var1 = "abc";
System.out.println(var1);
}
public static final void main() {
abc("a");
}
// $FF: synthetic method
public static void main(String[] var0) {
main();
}
}
2、分析
看这是生成了类的一个静态方法,this 当做参数传入