扩展功能的“ this @”语法

时间:2020-02-28 00:59:59

标签: kotlin

我正在尝试找出如何在this块中引用with

inline fun A.foo(bar: B, crossinline block: B.() -> Unit) {
    with (bar) {
        this@A.doSomething() // compile error, "unresolved reference @A"
        block()
    }
}

这是我的解决方法:

inline fun A.foo(bar: B, crossinline block: B.() -> Unit) {
    val self = this
    with (bar) {
        self.doSomething() // okay, but ugly
        block()
    }
}

有更好的方法吗,为什么不起作用?

1 个答案:

答案 0 :(得分:2)

我尝试代码 enter image description here

您可以使用this @ foo来访问A,或使用let代替

inline fun Activity.foo(bar: Fragment) {
    bar.let {
        this.xxx
    }
}