Kotlin使我能够通过委托给主要构造函数参数来实现接口,如下所示:

class Foo(xs : ArrayList<Int>) : List<Int> by xs { }

But this exhibits the backing implementer to the user. Delegating to an anonymous also seems to be ok:

class Foo() : List<Int> by ArrayList<Int>() { }

This hides the implementation details, but we loose access to features not provided by the interface, which in this case is mutability.

因此,我希望将实现委托给不在主构造函数中的属性.我想要的和

class Foo() : List<Int> by xs {
    val xs : List<Int> = ArrayList<Int>()
}

which doesn't compile.

是否有可能在类体中显式定义属性,并仍然能够将实现委托给它?

推荐答案

This is not currently possible. The expression in the by-clause is computed only once before the construction of the class, so you cannot reference symbols of that class.

虽然在Kotlin 1.0中几乎肯定不会支持这一点,但有一个request in the issue tracker可以允许这样做.

sometimes工作的一个有趣的解决方法是将希望成为委托的属性改为具有默认值的构造函数参数.这样,在by子句和类主体中都可以访问:

class Foo(val xs: List<Int> = ArrayList<Int>()) : List<Int> by xs {
    fun bar() {
        println(xs)
    }
}

Keep in mind though that xs in by xs is still calculated only once here, so even if xs is a var property, only the default value provided in the constructor will be used. It's not a universal solution, but sometimes it can help.

Kotlin相关问答推荐

在KMM合成多平台中创建特定于平台的视图

Kotlin多平台(KMP)保存到文件不能在iOS上保存

为什么Kotlin有次构造函数和init块?

找不到有效的 Docker 环境

如何在 Spring Boot 3 中为内部类提供运行时提示

如何从 var list 或可变列表中获取列表流

如何将 `throw` 放置在辅助函数中但仍然具有空安全性?

Kotlin 列表扩展功能

禁用 Android 12 默认启动画面

为什么 IntelliJ Idea 无法识别我的 Spek 测试?

@InlineOnly 注释是什么意思?

在 Kotlin 中取最后 n 个元素

为什么 Kotlin Pair 中的条目不可变?

面临一些未知问题一些后端jvm内部错误

Android 与 Kotlin - 如何使用 HttpUrlConnection

使用导航组件在不同的图形之间导航

Kotlin - computed var 属性的用处?

如何将 CameraView 与 Jetpack Compose 一起使用?

通过在 kotlin-gradle 中使用子项目Unresolved reference: implementation

Java的Kotlin:字段是否可以为空?