kotlin - 如何在内部类上调用函数

标签 kotlin

以下代码发布在Kotlin的网站上:

class A { // implicit label @A
    inner class B { // implicit label @B
        fun Int.foo() { // implicit label @foo
            val a = this@A // A's this
            val b = this@B // B's this

            val c = this // foo()'s receiver, an Int
            val c1 = this@foo // foo()'s receiver, an Int

            val funLit = lambda@ fun String.() {
                val d = this // funLit's receiver
            }


            val funLit2 = { s: String ->
                // foo()'s receiver, since enclosing lambda expression
                // doesn't have any receiver
                val d1 = this
            }
        }
    }
}

我不清楚您如何在内部类中调用函数。例如,如何调用Int.foo()
var a = A()
a.Int.foo() // This is not allowed.

最佳答案

让我们看一个更简单的例子:

class A { 

    inner class B { 

        fun foo() { 
          // ...
        }
    }
}

要在内部类中调用函数,必须使用外部类的实例访问它,如下所示:
A().B().foo()

使您的示例更加困难的是Int.foo()是扩展功能,因此要访问它,您必须在与扩展功能相同范围内的foo()上调用Int:
class A { // outer class A
    inner class B { // inner class B
        fun Int.foo() { // entension function foo
            print("Foo called on integer $this")
        }

        fun caller(i: Int) { // calls extension function
            i.foo()
        }
    }
}

fun main() {
    A().B().caller(10)   // calls extension function in inner class B
}

在这里,我们添加了一个函数caller,它与扩展函数的作用域相同。该代码输出以下内容:
Foo called on integer 10

关于kotlin - 如何在内部类上调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53390306/

相关文章:

android - 您如何使用 Room 和带有 LiveData 的 ViewModel 检索树结构,以便在包含子 RecyclerView 的 RecyclerView 中使用?

android - 如何让我的 flutter 应用程序意识到它是以不同的 Intent 启动的?

android - BuildConfig.DEBUG 是编译时常量吗?

java - 如何为 Retrofit 中的挂起功能创建调用适配器?

functional-programming - 如何在 Kotlin 中将函数声明为变量

java - 如何使用 Kotlin 中的 Flowable.generate

kotlin - 抛弃Kotlin箭头中的嵌套选项

javascript - kotlin中如何传递带有参数的函数引用?类似于javascript中的bind()

spring - Kotlin 的 Arrow <Exception, X> 和交易

spring - 使用 @ElementCollection 的查询的 DTO 投影导致 'Unable to locate appropriate constructor on class' 错误