首页 > 解决方案 > 在 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

标签: kotlin

解决方案


出现问题,因为没有printNumber参数的方法。你可以只使用test.hour.toString().

Kotlin 尝试将此变量转换为Int,正如它所看到的,您为变量设置了一个 int :test.hour = 25。但它不能,因为变量是可变的。


推荐阅读