有没有更优雅的方法来检查String在Kotlin中是否为有效的Int? [英] Is there a more elegant way to check if a String is a valid Int in Kotlin?

查看:292
本文介绍了有没有更优雅的方法来检查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.

这篇关于有没有更优雅的方法来检查String在Kotlin中是否为有效的Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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