Kotlin中的扩展字段 [英] Extension fields in Kotlin

查看:91
本文介绍了Kotlin中的扩展字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin中编写扩展方法很容易:

It's easy to write extension methods in Kotlin:

class A { }
class B {
    fun A.newFunction() { ... }
}

但是有什么方法可以创建扩展变量?喜欢:

But is there some way to create extension variable? Like:

class B {
    var A.someCounter: Int = 0
}

推荐答案

否-文档对此进行解释:

扩展实际上并不修改它们扩展的类.通过定义扩展,您无需在类中插入新成员,而只是使新函数可在该类的实例上以点符号进行调用.

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 instances of this class.

请注意,由于扩展程序实际上并未将成员插入类,因此,扩展属性没有有效的方法来拥有后备字段.这就是为什么扩展属性不允许使用初始化程序.只能通过显式提供getter/setter来定义其行为.

Note that, since extensions do not actually insert members into classes, there’s no efficient way for an extension property to have a backing field. This is why initializers are not allowed for extension properties. Their behavior can only be defined by explicitly providing getters/setters.

将扩展功能/属性仅视为用于调用静态函数并传递值的语法糖就可以了.

Thinking about extension functions/properties as just syntactic sugar for calling a static function and passing in a value hopefully makes this clear.

这篇关于Kotlin中的扩展字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆