grian
grian

Reputation: 318

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

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.

Upvotes: 0

Views: 1372

Answers (1)

gidds
gidds

Reputation: 18607

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.

Upvotes: 2

Related Questions