Is there a more elegant way to check if a String is a valid Int in Kotlin?

笑着哭i 提交于 2021-01-29 15:24:51

问题


This is Kotlin/JVM

I currently have this code :


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

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.


回答1:


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
    }

However, that still unnecessarily creates a String object.

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

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

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.



来源:https://stackoverflow.com/questions/65282335/is-there-a-more-elegant-way-to-check-if-a-string-is-a-valid-int-in-kotlin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!