首页 > 解决方案 > 无法在 kotlin 多平台中访问预期的类构造函数参数

问题描述

我目前正在使用 kotlin 开发一个多平台模块。为此,我依靠expect/actual机制

我声明了一个简单的类Common.kt

expect class Bar constructor(
    name: String
)

我想在通用方法中使用定义的类(也存在于 中Common.kt):

fun hello(bar: Bar) {
    print("Hello, my name is ${bar.name}")
}

实际实现定义在Jvm.kt

actual data class Bar actual constructor(
    val name: String    
)

问题是我的hello函数中出现以下错误

未解决的参考:名称

我究竟做错了什么?

标签: kotlinkotlin-multiplatformkmm

解决方案


预期的类构造函数不能有属性参数

因此,有必要将属性描述为类成员val name: String

'Bar' 的实际构造函数没有对应的预期声明

但是,要使实际的构造函数与预期的声明相匹配,参数的数量必须相同。这就是为什么除了属性的存在之外还要在构造函数中添加参数name: String

expect class Bar(name: String) {
    val name: String
}

actual class Bar actual constructor(actual val name: String)

注意:如果我们将预期类的构造函数留空,我们会看到 IDE 在当前类中添加构造函数时会抱怨不兼容。

总帐


推荐阅读