这感觉有点不一致,因为它使用的是独立函数,而不是类/接口方法:

class TestClass {
    val foo = "bar"
}

fun testScope(scope: TestClass.() -> Any) {

    val test = TestClass()

    scope(test)

}


// this works
fun TestClass.standaloneRunInTest() {
    println(foo)
}

interface Example {
    
    val name: String

    // but this doesn't?
    fun TestClass.interfaceRunInTest() {
        println(foo + name)
    }

    object Instance: Example {
        override val name: String = "Baz"
    }

}


fun main() {

    testScope {
        standaloneRunInTest() // prints "bar"
        Example.Instance.interfaceRunInTest() // expected to print "barbaz", but gets Unresolved reference: interfaceRunInTest
    }

}

不过,更有可能的是我在做一些愚蠢的事情!

推荐答案

Example.Instance不是TestClass的实例.您正在使用语法,就像您试图调用interfaceRunInTest()作为Example.Instance的函数一样,这是不起作用的.

要调用在类型作用域中定义的扩展函数,必须将这两种类型都作为接收者纳入作用域,例如:

testScope {
    Example.Instance.run { interfaceRunInTest() }
}

// or 
Example.Instance.run {
    testScope {
        interfaceRunInTest()
    }
}

对于此目的,runwith范围函数非常有用.

Kotlin相关问答推荐

为什么可组合对象看似无状态(唯一传递的参数是函数,而不是状态),但会进行重组

限制通用Kotlin枚举为特定类型

如何从 Period.between() 返回的字符串中提取信息? (Kotlin )

为什么记得不将 StateFlow 转换为特定类型?

如何将字符串格式化为电话号码kotlin算法

Kotlin:不允许在辅助构造函数参数上使用val

如何使 TextInputEditText 只读?

如何在 android jetpack compose 中相互重叠列表项?

Kotlin 类的调用方法

将 Firebase 数据快照反序列化为 Kotlin 数据类

如何在Spring Boot应用程序上启用承载身份验证?

Android:在 DAO 中使用 Room 数据库和 LiveData 架构

Ktor 在 java.library.path 中没有 netty_transport_native_epoll_x86_64

使用Dagger 2提供函数依赖性

添加抽象的私有getter和公共setter的正确方法是什么?

如何在 Jetpack Compose 的 LazyColumn/LazyRow 中禁用和启用滚动?

类型不匹配:推断类型为 LoginActivity 但应为 LifecycleOwner

(kotlin的Moshi)@Json vs@field:Json

Kotlin 警告:Conditional branch result of type ... is implicity cast of Any?

lateinit 的 isInitialized 属性在伴随对象中不起作用