kotlin - 在 kotlin 中使用委托时,为什么我会收到关于“智能演员”的错误?
问题描述
我在 Kotlin 中创建了一个 Delegate 类,用于“循环”变量,例如小时:
当“25”与初始值为“0”的小时相加时,结果应该为“1”,因为没有“25”小时这样的东西。
我创建的类有效,但是当我重新分配这样一个委托变量,然后使用'print(...)'打印它时,我收到一个错误,说'智能转换是不可能的,X 是一个可变变量'
难道我做错了什么 ?我该如何解决这个问题?
我试图添加一个明确的演员表,这有所帮助,但给出了一个警告说“不需要演员表”,而没有演员表它就不起作用。
这是重现错误的最少代码:
package <package name>
import kotlin.reflect.KProperty
fun main(){
val test = Test()
test.hour = 25
print(test.hour)
// this works: print(test.hour as Number) ("No cast needed")
}
// just a class which uses the delegate
class Test {
var hour by CyclicVariable(24)
}
// the delegate class
class CyclicVariable(val max: Number, var value: Number = 0){
operator fun getValue(reference: Any?, property: KProperty<*>): Number = value.toDouble()
operator fun setValue(reference: Any?, property: KProperty<*>, value: Number) {
val result = value.toDouble() % max.toDouble()
this.value = if (result >= 0) result else max.toDouble() + result
}
}
预期结果:1.0
在控制台上
实际结果:
Error:(12, 11) Kotlin: Smart cast to 'Int' is impossible, because 'test.hour' is a mutable property that could have been changed by this time
解决方案
出现问题,因为没有print
带Number
参数的方法。你可以只使用test.hour.toString()
.
Kotlin 尝试将此变量转换为Int
,正如它所看到的,您为变量设置了一个 int :test.hour = 25
。但它不能,因为变量是可变的。
推荐阅读
- c# - 从手动管理的 HttpClient(带有单独的 TokenUri)迁移到 IHttpClientFactory
- java - 将数据插入数据库 - SQLException
- javascript - 如何使 div 刷新?
- excel - 是否可以在 Word 中以相当简单的方式从 VBA 调用 Excel 加载项?
- javascript - 如何删除角垫按钮切换悬停效果?
- php - 我怎样才能正确地抽象这个刀片模板@foreach?
- python - 使用 Spyder 安装/使用软件包时遇到问题
- angular - 使用 Angular 9 安装 Firebase 时出错:firebase/app
- java - C# 的 DateTime.ToFileTimeUTC 在 java 中是否可比?
- python-3.x - 训练后损失和准确率保持不变