如何将 String 转换为 Int 和 Long?
How to cast String into Int and Long?
在Java
中我们使用
Integer.valueOf(str)
和
Long.valueOf(str)
获得 integer
但我们怎样才能在 Kotlin
中做同样的事情?
您可以只使用 toInt
, toLong
和类似的转换扩展。
例如:
val i: Int = str.toInt()
val l: Long = str.toLong()
还有 toIntOrNull
等,以防您的字符串可能不是有效数字:
val i: Int? = str.toIntOrNull()
Kotlin 有针对 String class 的扩展方法,它们的功能相同但更优雅。
str.toInt()
str.toLong()
请注意,您也可以自己编写 extension methods。
Kotlin define extension function in StringNumberConversions.kt like toInt, toLong 等。这些函数在内部调用标准 java 函数,例如
java.lang.Integer.parseInt(...)
或 java.lang.Long.parseLong(...)
您可以像这样使用它们:
"123".toInt()
"123".toLong()
这些是可用于 Strings
在 KOTLIN 中解析的扩展方法:
str.toBoolean()
str.toInt()
str.toLong()
str.toFloat()
str.toDouble()
str.toByte()
str.toShort()
不如
val str = ""
val quotaInteger = str.toDouble().toInt()
cos sometime end give us like "123.22", 如果我们使用 toInt(),它会抛出 NumberFormatException
在Java
中我们使用
Integer.valueOf(str)
和
Long.valueOf(str)
获得 integer
但我们怎样才能在 Kotlin
中做同样的事情?
您可以只使用 toInt
, toLong
和类似的转换扩展。
例如:
val i: Int = str.toInt()
val l: Long = str.toLong()
还有 toIntOrNull
等,以防您的字符串可能不是有效数字:
val i: Int? = str.toIntOrNull()
Kotlin 有针对 String class 的扩展方法,它们的功能相同但更优雅。
str.toInt()
str.toLong()
请注意,您也可以自己编写 extension methods。
Kotlin define extension function in StringNumberConversions.kt like toInt, toLong 等。这些函数在内部调用标准 java 函数,例如
java.lang.Integer.parseInt(...)
或 java.lang.Long.parseLong(...)
您可以像这样使用它们:
"123".toInt()
"123".toLong()
这些是可用于 Strings
在 KOTLIN 中解析的扩展方法:
str.toBoolean()
str.toInt()
str.toLong()
str.toFloat()
str.toDouble()
str.toByte()
str.toShort()
不如
val str = ""
val quotaInteger = str.toDouble().toInt()
cos sometime end give us like "123.22", 如果我们使用 toInt(),它会抛出 NumberFormatException