Kotlin:可见性修饰符更改匿名对象的类型

Kotlin: Visibility modifier changes type of anonymous object

在以下工作代码中删除 myScope(第 4 行)的 private 修饰符将破坏代码。原因是 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.