我想在Kotlin中使用when()表达式从函数返回不同的值.输入是String,但它可能可以被解析为Int,所以如果可能的话,我想返回解析后的Int,如果不是的话,返回String.由于输入是String,我不能使用is类型判断表达式.

Is there any idiomatic way to achieve that?

Edit: My problem is how the when() expression should look like, not about the return type.

推荐答案

Version 1 (using toIntOrNull and when when as requested)

fun String.intOrString(): Any {
    val v = toIntOrNull()
    return when(v) {
        null -> this
        else -> v
    }
}

"4".intOrString() // 4
"x".intOrString() // x

Version 2 (using 100 and the elvis operator 101)

when is actually not the optimal way to handle this, I only used when because you explicitely asked for it. This would be more appropriate:

fun String.intOrString() = toIntOrNull() ?: this

Version 3 (using exception handling):

fun String.intOrString() = try { // returns Any
   toInt()
} catch(e: NumberFormatException) {
   this
}

Kotlin相关问答推荐

Kotlin中的增广赋值语句中的难以理解的错误

在KMM合成多平台中创建特定于平台的视图

解决Microronaut中多个可能的Bean候选者冲突

在调用父构造函数之前重写类属性

仅某些用户出现 DateTimeFormatter 错误

Kotlin 说不需要强制转换,但删除后会出现新警告

try 一次性插入多条记录时,JOOQ连接为空错误

Kotlin 基于参数类型的返回类型推断

协程子作业(job)取消

通用接口继承

关于 Kotlin 函数类型转换的问题

如何在 kotlin 中通过反射设置委托属性值?

Kotlin 使用迭代索引过滤 lambda 数组

Moshi:解析单个对象或对象列表(kotlin)

Dagger 2 ContributesAndroidInjector 为模块提供活动

在协程中等待侦听器内的数据

包括登录Elvis operator?

在 Scaffold Jetpack Compose 内的特定屏幕上隐藏顶部和底部导航器

如何将 Kotlin 日期中的字符串或时间戳格式化为指定的首选格式?

android Room 将 Null 作为非 Null 类型返回