gpt4 book ai didi

kotlin - 如何使用委托(delegate) 'by' 在 Kotlin 中获取对委托(delegate)实例的引用?

转载 作者:IT老高 更新时间:2023-10-28 13:47:19 25 4
gpt4 key购买 nike

有没有办法在 Kotlin 中获取对委托(delegate)对象的引用? 这是一个例子:

interface A {
fun test()
}
class B: A {
override fun test() {
println("test")
}
}
class C: A by B() {
override fun test() {
// ??? how to get a reference to B's test() method?
}
}

最佳答案

目前无法直接执行此操作。您可以通过将其存储在主构造函数中声明的属性中来实现,如下所示:

class C private constructor(
private val bDelegate: B
) : A by bDelegate {
constructor() : this(B())

/* Use bDelegate */
}

关于kotlin - 如何使用委托(delegate) 'by' 在 Kotlin 中获取对委托(delegate)实例的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52246401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com