Kotlin inner class 无法解析在 outer class 中声明的扩展函数
Kotlin inner class can't resolve extension function declared in outer class
为什么 Kotlin 中的 inner class 无法访问在 outer class 中声明的扩展函数,如下所示:
class A{
val a = "as".foo() // LINE 1
class B{
val b = "as".foo() // LINE 2
}
fun String.foo(){}
}
在 LINE 1
上扩展功能已解决,但在 LINE 2
上该功能未解决。想知道为什么会有这样的限制?
这不是内部 class,因为您没有在上面使用关键字 inner
。它只是一个嵌套的 class。如果您熟悉 Java,它就像一个 static
内部 class。由于它不是 inner
,因此它没有对外部 class 的任何隐式引用,并且不能对外部 class 的成员进行裸调用,因为没有特定的实例来使用的成员。但是,它可以在外部 class 的实例上调用外部 class 的成员,因此您可以执行以下操作:
class A{
val a = "as".foo()
class B{
val b = A().run { "as".foo() }
}
fun String.foo(){}
}
尽管 foo
是一个扩展函数,但由于它的声明位置,它也是 A 的成员。使用使 class 成为范围内接收器的范围函数是从另一个 class.
调用其成员扩展函数之一的一种方法
编辑:这是您想要在 class.
中声明扩展的原因之一的示例
class Sample(val id: Int) {
private val tag = "Sample#$id"
fun String.alsoLogged(): String{
Log.d(tag, this)
return this
}
}
您可以使用此扩展轻松记录您在 class 中使用的字符串(或者当它是 run
或 apply
的接收者时)。在 class 之外声明是没有意义的,因为它使用 class.
的私有 tag
属性
这是因为 Kotlin 将您的代码编译为
public final class A {
@NotNull
private final Unit a;
@NotNull
public final Unit getA() {
return this.a;
}
public final void foo(@NotNull String $this$foo) {
Intrinsics.checkNotNullParameter($this$foo, "$this$foo");
}
public A() {
this.foo("as");
this.a = Unit.INSTANCE;
}
public static final class B {
public B() {
// You can't access A's foo() method here.
}
}
}
为什么 Kotlin 中的 inner class 无法访问在 outer class 中声明的扩展函数,如下所示:
class A{
val a = "as".foo() // LINE 1
class B{
val b = "as".foo() // LINE 2
}
fun String.foo(){}
}
在 LINE 1
上扩展功能已解决,但在 LINE 2
上该功能未解决。想知道为什么会有这样的限制?
这不是内部 class,因为您没有在上面使用关键字 inner
。它只是一个嵌套的 class。如果您熟悉 Java,它就像一个 static
内部 class。由于它不是 inner
,因此它没有对外部 class 的任何隐式引用,并且不能对外部 class 的成员进行裸调用,因为没有特定的实例来使用的成员。但是,它可以在外部 class 的实例上调用外部 class 的成员,因此您可以执行以下操作:
class A{
val a = "as".foo()
class B{
val b = A().run { "as".foo() }
}
fun String.foo(){}
}
尽管 foo
是一个扩展函数,但由于它的声明位置,它也是 A 的成员。使用使 class 成为范围内接收器的范围函数是从另一个 class.
编辑:这是您想要在 class.
中声明扩展的原因之一的示例class Sample(val id: Int) {
private val tag = "Sample#$id"
fun String.alsoLogged(): String{
Log.d(tag, this)
return this
}
}
您可以使用此扩展轻松记录您在 class 中使用的字符串(或者当它是 run
或 apply
的接收者时)。在 class 之外声明是没有意义的,因为它使用 class.
tag
属性
这是因为 Kotlin 将您的代码编译为
public final class A {
@NotNull
private final Unit a;
@NotNull
public final Unit getA() {
return this.a;
}
public final void foo(@NotNull String $this$foo) {
Intrinsics.checkNotNullParameter($this$foo, "$this$foo");
}
public A() {
this.foo("as");
this.a = Unit.INSTANCE;
}
public static final class B {
public B() {
// You can't access A's foo() method here.
}
}
}