有没有更优雅的方法来检查String在Kotlin中是否为有效的Int?

问题描述:

这是Kotlin/JVM

This is Kotlin/JVM

我目前有此代码:


fun String.isValidInt(): Boolean {
    var isInt: Boolean = false
    try {
        if (this.toInt().toString() == this) {
            isInt = true
        } 
    } catch (e: NumberFormatException) {
        isInt = false
    }
    return isInt
}

我想知道是否有更优雅的方法来实现此目的,特别是将返回值isInt设置为true或false的方式.

and I was wondering if there was a more elegant way to approach this, specficially the way I set the return value isInt to true or false.

此处是我的代码的游乐场链接,也是进行测试的主要功能.

Here is a playground link to my code and a main function to test with.

首先,try可以返回表达式.与使用函数体的表达形式一起,删除冗余的ifthis,并避免使用局部变量,它变为:

For a start, try can return an expression. Together with using the expression form of the function body, removing the redundant if and this, and avoiding the local variable, it becomes:

fun String.isValidInt()
    = try {
        toInt().toString() == this
    } catch (x: NumberFormatException) {
        false
    }

但是,它仍然不必要地创建String对象.

However, that still unnecessarily creates a String object.

有一个 toIntOrNull() 函数,它将使其更简单,更高效:

There's a toIntOrNull() function which would make it simpler and more efficient:

fun String.isValidInt() = toIntOrNull() != null

请注意,在所有这些情况下,它实际上都是在执行转换(并丢弃结果).在大多数情况下,我希望您希望使用该结果,因此最好直接调用代码toIntOrNull().

Note that in all these cases it's actually performing the conversion (and discarding the result). In most cases, I'd expect you want to use the result, so you may be better off having your code call toIntOrNull() directly.