Kotlin-ExtensionFunctions(扩展函数)实现原理分析

更新时间:2023-06-24 09:39:16 阅读: 评论:0

Kotlin-ExtensionFunctions(扩展函数)实现原理分析
kotlin中的扩展函数,实际上是在⾃⼰的类中添加了⼀个static final⽅法,将需要扩展的类,在使⽤的时候作为第⼀个参数传⼊⽅法中,然后使⽤。⽐如:
在ExtensionTest.kt中的顶级函数
fun String.hello(str: String): String{
return "hello" + str + this.length
杭州景点门票}
fun String.hello1(str: String): String{
return "hello$str"
}
经过反编译之后⽣成字节码如下:
public final class ExtensionTestKt {
@NotNull英语句式
public static final String hello(@NotNull String $receiver, @NotNull String str) {
Intrinsics.checkParameterIsNotNull($receiver, "$receiver");
Intrinsics.checkParameterIsNotNull(str, "str");
return "hello" + str + $receiver.length();
}
氮相对原子质量@NotNull
public static final String hello1(@NotNull String $receiver, @NotNull String str) {
Intrinsics.checkParameterIsNotNull($receiver, "$receiver");
Intrinsics.checkParameterIsNotNull(str, "str");
return "hello" + str;
}
}
这其实就变成了在ExtensionTestKt这个类中的两个static final⽅法,⽽原先对String类型进⾏扩展,其实就是将调⽤扩展函数的调⽤者作为函数的第⼀个参数传⼊。
kotlin中的扩展函数,实际上就是通过给类添加public static final函数的做法来实现,这样做可以减少utils类的使⽤
扩展函数是静态解析的,是采⽤静态分派的过程来处理。这意味着调⽤的扩展函数是由函数调⽤所在的表达式的类型来决定的, ⽽不是由表达式运⾏时求值结果决定的。这意思其实就是在使⽤该扩展函数的时候,如果类本⾝和其⼦类都进⾏了同⼀个函数的扩展,这函数是不会有重写关系的,在使⽤的时候,只会根据需要使⽤该⽅法的对象的实际类型来决定是调⽤了哪个,就是相当于调⽤静态⽅法。⽽不是动态分派。⽐如:
open class Shape
class Rectangle: Shape()
Name() = "Shape"
脚手架剪刀撑
Name() = "Rectangle"
fun printClassName(s: Shape) {
Name())
}
卵母细胞
printClassName(Rectangle())
这⾥的输出结果是Shape
其实很明显,因为扩展函数就是相当于⼀个静态⽅法,⽽调⽤静态⽅法是没有重写,所以⼦类并不会影响⽗类。
如果⼀个类定义有⼀个成员函数与⼀个扩展函数,⽽这两个函数⼜有相同的接收者类型、 相同的名字,并且都适⽤给定的参数,这种情况总是取成员函数。
class Example {
天体营的故事fun printFunctionType() { println("Class method") }少女心头像动漫
安全生产专题会议
}
fun Example.printFunctionType() { println("Extension function") }
Example().printFunctionType()
这段代码输出“Class method”。

本文发布于:2023-06-24 09:39:16,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/1027776.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:函数   扩展   决定   类型   静态
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图