为内部类创建扩展函数时,如何从内部类访问外部作用域?
例子
class A {
inner class B {
fun own() = this@A
}
}
Run Code Online (Sandbox Code Playgroud)
此代码按预期编译和执行。
当我添加以下扩展功能时
fun A.B.ext() = this@A
Run Code Online (Sandbox Code Playgroud)
编译失败
Error:(7, 22) Kotlin: Unresolved reference: @A
Run Code Online (Sandbox Code Playgroud)
我阅读了限定 this的文档,它简要提到了扩展功能,但没有任何示例。
是否可以从扩展函数访问外部作用域?
扩展函数只能做非扩展fun ext(x: A.B)可以做的事情,所以我希望不会,就像你无法在 Java 中访问它一样。这是因为它编译成这样一个函数,语法只是让它看起来像一个成员。
虽然类B有一个包含对外部A实例的引用的字段,但无法通过名称直接从代码访问该字段。允许访问它会违反封装性。
this链接页面讨论了“从外部范围访问”。这里的“范围”是指https://en.wikipedia.org/wiki/Scope_(computer_science),因此在示例中,您的范围的注释中写着“隐式标签”
class A { // outer scope 1
inner class B { // outer scope 2
fun Int.foo() { // function scope
}
}
}
Run Code Online (Sandbox Code Playgroud)
尽管
fun A.B.ext() = ...
Run Code Online (Sandbox Code Playgroud)
没有任何外部作用域(文件作用域除外,它没有this)。除非真的是
class C {
fun A.B.ext() = // can use this@C
}
Run Code Online (Sandbox Code Playgroud)
但您不能编写this@Aor ,因为this@B该函数未在class Aor的范围内定义class B。
| 归档时间: |
|
| 查看次数: |
207 次 |
| 最近记录: |