- Kotlin进阶实战
- 沈哲 易庞宙编著
- 512字
- 2025-02-20 21:22:45
4.4 扩展属性
类似于扩展函数,Kotlin还支持扩展属性。扩展属性实际上不会向类添加新的成员,也不能更改类的内容。
扩展属性是把某些函数添加为数据,可以直接通过“=”设置或使用。扩展属性可以通过val或者var进行修饰。如果是val修饰的扩展属性,就需要定义get方法。如果是var修饰的扩展属性,就需要定义get和set方法。

执行结果如下:
this is a text property
如图4-4所示,查看上述代码的字节码,可知Extension3的扩展属性text实际上是以static方法出现在Extension3Kt类中,而不是在原先的Extension3类中添加了一个text属性。

图4-4 Extension3的字节码
真正使用extension3.text时,只是调用Extension3Kt的getText()方法,如图4-5所示。

图4-5 extension3.text的字节码
INVOKESTATIC Extension3Kt.getText (LExtension3;)Ljava/lang/String;
举一个例子,对Android中的Context添加一个属性isNetworkAvailable:

之后,只要使用到Context的地方都可以使用isNetworkAvailable属性来判断网络的可用情况。
再举一个例子,对Android的View进行扩展。最初对View添加一个扩展函数:
fun <T : View> T.click(block: (T) -> Unit) = setOnClickListener { block(it as T) }
它虽然能够简化代码,但是不能防止View被重复点击。
于是,结合扩展函数和扩展属性的特性来优化刚才的代码:


这样一来,对View增加了多个扩展函数,也可以满足多种使用场景。
(1)普通事件的单击:

(2)默认600毫秒内防止重复的单击:

它等价于:

(3)1秒内防止重复的点击:

它等价于:

上述代码还可以继续优化,再结合埋点的SDK(无埋点除外),还能简化埋点的处理。