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

标签 kotlin extension-methods class-visibility

删除 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 中的两个版本:
enter image description here

最佳答案

此行为是设计使然。见 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/

相关文章:

python - 如何从 .pyo 文件恢复源 python 代码 (.py)?

C++,如何将派生类转换为 protected 基类?

对计算属性的 Swift 访问控制 : why does this work?

java - 默认情况下,Java 和 C++ 中的类是私有(private)的还是公有的?

android - Kotlin - 无法解析的日期

Dart 扩展 : don't access members with 'this' unless avoiding shadowing

android - Kotlin:缺少为 kaptDebugKotlin 提出的 kotlin.jvm.internal.FunctionReferenceImpl

c# - 如何在单元测试期间覆盖 IQueryable 的 Contains 方法?

android - 如何使用导航架构组件修复动态功能模块中 fragment 的发布版本中的 ClassNotFoundException?

spring - 如何解析和修改build.gradle.kts Kotlin Gradle构建脚本?