如何在kotlin的lambda表达式中获取类示例?

wwtsj6pe  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(324)

在java中,当我想从内部类获取外部类示例时,我正在编写outclass.this。在kotlin中,在lambda表达式中,如果lambda与接收器一起运行,是否有方法获取编写lambda表达式的类的示例?假设我们有以下代码:

class Dog
{
    fun funcA () : Unit
    {
        println("Dog funcA")
    }
}  
class OuterClass
{ 
   var d : Dog = Dog()
   fun funcA () : Unit
   {
        println("OuterClass funcA")
   }

  fun funcWithLambda() : Unit
  {
      d.apply(){
         //place where I want to call OutClass method *funcA*
         // writing *this* will refer to *Dog* instance
         }
  }
}
wfsdck30

wfsdck301#

你在找什么 this@OuterClass.funcA() .

xzlaal3s

xzlaal3s2#

我对标签过敏,所以我更喜欢给显式命名的变量赋值:

val outer: OuterClass = this
d.apply() {
    val inner: Dog = this
    outer.funcA()
    inner.funcA()
}

更好的是避免不同的 this 完全是上下文(显然你的例子是人为的,所以这个例子也是):

fun funcWithoutLambda(): Unit {
    funcA()
    d.funcA()
}

相关问题