如何在何时查找字符串是否为数字的情况下使用Kotlin? [英] How to use Kotlin when to find if a string is numeric?

查看:685
本文介绍了如何在何时查找字符串是否为数字的情况下使用Kotlin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to use a when() expression in Kotlin to return different values from a function. The input is a String, but it might be parsable to an Int, so I'd like to return the parsed Int if possible, or a String if it is not. Since the input is a String I can not use the is type check expression.

有没有惯用的方法来实现这一目标?

Is there any idiomatic way to achieve that?

我的问题是when()表达式的外观,而不是返回类型.

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

推荐答案

版本1(使用

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

版本2(使用 toIntOrNull 和Elvis运算符?:)

Version 2 (using toIntOrNull and the elvis operator ?:)

when实际上不是处理此问题的最佳方法,我只使用了when,因为您明确要求它.这样会更合适:

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

版本3(使用异常处理):

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

这篇关于如何在何时查找字符串是否为数字的情况下使用Kotlin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆