I have an attribute in my model defined as above that in some cases contain an Int.

var value: Any?

我知道,如果我先将其转换为字符串,然后再转换为Int,我就能做到这一点

value.toString().toInt() // works

有没有办法跳过之前的字符串投射呢? 当我try 将直接强制转换为Int时,收到以下错误

FATAL EXCEPTION: main
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

推荐答案

问题是,您试图将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.

Kotlin相关问答推荐

何时使用figureEach

捕捉异常是Kotlin协程中的反模式吗?

为什么不';Kotlin是否在数据类构造函数中隐式分配null值可为null的字段?

Kotlin - 什么时候和什么时候不喜欢内联函数,为什么?

为什么 <= 可以应用于 Int 和 Long,而 == 不能?

如何访问嵌套在另一个 map 中的 map 中的值(在 kotlin 中)

如何通过 compose 处理剪切区域?

Kotlin 日期格式从一种更改为另一种

为什么没有remember 的 mutableStateOf 有时会起作用?

Android 导航组件 - 向上导航打开相同的片段

Android 在将 androidx 生物识别更新为 1.0.0-alpha04 后崩溃

API 'variant.getJavaCompile()' 已过时

Kotlin中具有多个参数的绑定适配器

Android 上的 Kotlin:将map到list

Kotlin 中更好的回调方法是什么?侦听器与高阶函数

在 Kotlin 中创建非绑定服务

可以在函数参数中使用解构吗?

Kotlin中的函数接口

使用 java lambda 调用 kotlin 函数时,Kotlin 无法访问 kotlin.jvm.functions.Function1

从另一个列表创建一个列表