Kotlin 如何在"return (object : interface) { }"中使用它


class AImpl : A {
override fun createB(): B {
return object : BImpl {
val t = this
override fun createC(): C {
return CBuilderInstance.buildC { // this: CBuilder
this.B = t // type: B
// How can I use 'this@Something' to replace the t.
}
}
}
}
}
class CBuilder {
fun buildC(block: CBuilder.() -> Unit): C {
...
}
}

对不起,我无法描述我遇到的问题。

如何替换"t"在代码里?IDE给了我2个建议,"这个";和"this@AImpl",这是不工作的

根据Kotlin语言规范- this-表达式,一个带标签的this-表达式可以有以下形式:

  • this@type
  • this@function
  • this@lambda
  • this@outerFunction

后3种形式指的是函数/lambdas的隐式接收器,这显然不是你想要的。您想要引用由对象字面值object : BImpl { ... }创建的对象。

规范说(强调我的):

this@type,其中type当前所声明的任何分类器的名称(即,该表达式位于分类器声明的内部作用域),指所声明类型的隐式对象;

同样在分类器声明中,它说,

重要:对象字面量类似于对象声明,被认为是匿名分类器声明,尽管是表达式。

因此,尽管对象字面量是分类器声明,但它们没有一个可以写在@后面的名称。

综上所述,在不改变其他内容的情况下,不能在这里使用带标签的this表达式。

例如,您可以声明一个局部类,其名称为:
class AImpl : A {
override fun createB(): B {
class Foo : BImpl {
override fun createC(): C {
return CBuilder.buildC {
this.B = this@Foo
}
}
}
return Foo()
}
}

相关内容

最新更新