删除 private
myScope
的修饰符以下工作代码中的(第 4 行)将破坏代码。原因是 myScope
的类型发生了变化。 .可见性是否设置为 private
类型是:anonymous object : Scope
.无 private
类型切换为Scope
.我该如何解决这种行为?
interface Scope
operator fun<SD: Scope> SD.invoke(block: SD.() -> Unit) = block()
private val myScope = object : Scope {
fun Int.myScopedExtFunction() = 1337
}
fun usage() {
myScope {
1.myScopedExtFunction()
}
}
这是 Android Studio 中的两个版本:
最佳答案
此行为是设计使然。见 documentation :
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.
关于Kotlin:可见性修饰符更改匿名对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52892467/