kotlin - 无法在 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
函数中出现以下错误
未解决的参考:名称
我究竟做错了什么?
解决方案
预期的类构造函数不能有属性参数
因此,有必要将属性描述为类成员val name: String
'Bar' 的实际构造函数没有对应的预期声明
但是,要使实际的构造函数与预期的声明相匹配,参数的数量必须相同。这就是为什么除了属性的存在之外还要在构造函数中添加参数。name: String
expect class Bar(name: String) {
val name: String
}
actual class Bar actual constructor(actual val name: String)
注意:如果我们将预期类的构造函数留空,我们会看到 IDE 在当前类中添加构造函数时会抱怨不兼容。
总帐
推荐阅读
- django - 仅使用卡号 Visa/MasterCard 等进行支付集成 | 没有 Stripe,没有 Paypal,没有 PayTm,没有 RazorPay 等
- image-processing - 通过两个循环计算两个图像之间的 MSE
- reactjs - 使用反应组件作为值导出键/值对象的打字稿
- r - 将第一行变成一列
- python - 结合 WHEN 和聚合函数
- azure - ADF 用户属性“新建”按钮已禁用
- r - 跟踪栅格中非 na 像元的路径
- mongodb - Mongo DB - 嵌套/嵌入文档键的计数
- javascript - 将 html 转换为等效的单行文件,去掉多余的空格?
- .net - lavalink 的 Discord.net 托管问题