gpt4 book ai didi

kotlin - 匿名对象的方法范围-Kotlin

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

在Kotlin中,如果我在匿名对象上定义方法,有时可以访问它,而其他时候则不能。这似乎与范围规则有关,但我不确定。

在下面的代码示例中,对example3.field.method()的访问将导致编译错误。有趣的是,example2.field.method()可以正常编译。

以下行为的解释可能是什么?

class Example3 {
val field = object {
fun method() {}
}
}

fun showcase() {
val example1 = object {
fun method() {}
}
example1.method()
println(example1::class.qualifiedName)

class Example2 {
val field = object {
fun method() {}
}
}

val example2 = Example2()
example2.field.method()
println(example2::class.qualifiedName)

val example3 = Example3()
// example3.field.method() // won't compile
println(example3::class.qualifiedName)
}

最佳答案

从docs Object Expressions and Declarations:

Note that anonymous objects can be used as types only in local and private declarations. If you use an anonymous object as a return type of a public function or the type of a public property, the actual type of that function or property will be the declared supertype of the anonymous object, or Any if you didn't declare any supertype. Members added in the anonymous object will not be accessible.



在下面的代码示例中演示:
class Example4{
val publicObj = object{
val x = 1
}

private val privateObj = object{
val x = 2
}

fun showcase(){
val scopedObj = object{
val x = 3
}
println(publicObj.x) // ERROR : unresolved reference: x
println(privateObj.x) // OK
println(scopedObj.x) // OK
}
}

关于kotlin - 匿名对象的方法范围-Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56292961/

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