gpt4 book ai didi

kotlin - 在Kotlin接收器对象和扩展上

转载 作者:行者123 更新时间:2023-12-02 13:06:39 24 4
gpt4 key购买 nike

我试图熟悉更高级的Kotlin功能,但是我不知道为什么我的小代码示例在不打印“Test B”的同时编译并打印“Test A”。
谁能告诉我为什么不打印测试B?

class One{
fun delegate(operation: One.()-> Unit){
operation()
}
fun main(args: Array<String>){
val one= One()
fun One.doIt(){
println("Test A")
}
one.delegate { doIt() } //prints Test A
one.delegate {
fun One.doItDifferently(){
println("Test B") //not printed
}
}
}

最佳答案

这是因为您没有调用函数.toItDifferently(),而是仅对其进行定义(它是local function,即在另一个函数内部定义的函数)。修改您的示例以调用该函数:

one.delegate {
fun One.doItDifferently(){
println("Test B")
}
doItDifferently() // <- here
}

(UPD,基于注释)您可以使用 anonymous function调用 delegate,如下所示:
one.delegate( // note the parenthesis, not the curly braces
fun One.(){
println("Test B")
}
)

关于kotlin - 在Kotlin接收器对象和扩展上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45614034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com