问题
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