有没有更优雅的方法来检查 String 是否是 Kotlin 中的有效 Int?
Is there a more elegant way to check if a String is a valid Int in Kotlin?
这是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
}
我想知道是否有更优雅的方法来解决这个问题,特别是我将 return 值 isInt
设置为 true 或 false 的方法。
Here 是我的代码的游乐场 link 和测试的主要功能。
首先,try
可以 return 一个表达式。连同使用函数体的表达形式,去掉多余的if
和this
,避开局部变量,就变成:
fun String.isValidInt()
= try {
toInt().toString() == this
} catch (x: NumberFormatException) {
false
}
但是,这仍然不必要地创建了一个 String 对象。
有一个 toIntOrNull()
函数可以使它更简单、更高效:
fun String.isValidInt() = toIntOrNull() != null
请注意,在所有这些情况下,它实际上是在执行转换(并丢弃结果)。在大多数情况下,我希望您想要使用结果,因此您最好直接调用代码 toIntOrNull()
。
这是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
}
我想知道是否有更优雅的方法来解决这个问题,特别是我将 return 值 isInt
设置为 true 或 false 的方法。
Here 是我的代码的游乐场 link 和测试的主要功能。
首先,try
可以 return 一个表达式。连同使用函数体的表达形式,去掉多余的if
和this
,避开局部变量,就变成:
fun String.isValidInt()
= try {
toInt().toString() == this
} catch (x: NumberFormatException) {
false
}
但是,这仍然不必要地创建了一个 String 对象。
有一个 toIntOrNull()
函数可以使它更简单、更高效:
fun String.isValidInt() = toIntOrNull() != null
请注意,在所有这些情况下,它实际上是在执行转换(并丢弃结果)。在大多数情况下,我希望您想要使用结果,因此您最好直接调用代码 toIntOrNull()
。