所以,由于缺少像Long这样的方法。valueOf(字符串s)我卡住了。

如何将字符串转换为长在Kotlin?


当前回答

string.toLong()

其中字符串是变量。

其他回答

string可以使用扩展方法将它们解析为其他基本类型。在下面的例子:

“真正的”toBoolean()。 “10 . 0”toFloat()。 “10 . 0”toDouble()。 “10”toByte(。) “10”toShort(。) “10”toInt(。) “10”请(。)

注:回答中提及喷气机。字符串过时。以下是当前的Kotlin (1.0):

Kotlin中的任何字符串都有一个扩展函数,可以调用toLong()。不需要什么特别的东西,就用它吧。

String的所有扩展函数都有文档。你可以在api参考中找到其他标准库

实际上,有几种方法:

考虑到:

var numberString : String = "numberString" 
// number is the Long value of numberString (if any)
var defaultValue : Long    = defaultValue

然后我们有:

+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString is a valid number ?            |  true    | false                 |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toLong()                       |  number  | NumberFormatException |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toLongOrNull()                 |  number  | null                  |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toLongOrNull() ?: defaultValue |  number  | defaultValue          |
+—————————————————————————————————————————————+——————————+———————————————————————+

实际上,90%的情况下你还需要检查long是否有效,所以你需要:

"10".toLongOrNull()

有一个'orNull'等效的每个'toLong'的基本类型,这些允许管理无效的情况与Kotlin?习语。

String有相应的扩展方法:

"10".toLong()