问题是,您试图将cast直接从字符串转换为带value as Int
的整数.
这不起作用,因为正如异常告诉您的那样,value
包含一个字符串,不能将字符串强制转换为Int.这个字符串表示整数的事实并不重要,因为它需要被解析为Int.toInt()
方法正是这样做的.
The reason you must cast to a String first is because toInt()
is an extension method on String, and value
is of type Any?
. This means that you can't call toInt()
directly on value
because it doesn't know that it contains a String at compile time, even though it does at runtime. If you wanted to skip this step, you could also use smart casts by checking the type first:
if (value is String) {
value.toInt()
}
你可以在这里找到更多关于smart Cast和其他Kotlin类型casting的信息:https://kotlinlang.org/docs/reference/typecasts.html#smart-casts
This also may be pointing to an underlying design problem. You expect that this will sometimes contain an Int, but as we can see here whatever is setting this value in your model is setting it to a String containing that number. Do you expect this value to truly be able to contain many different types, or are you only expect Int and String? If the latter, then it would possibly be a better design decision to make this a String rather than an Any?
. That would prevent unexpected/unhandled types from being provided, and make the model less ambiguous to anyone looking at or using it.