
上QQ阅读APP看书,第一时间看更新
How it works...
Kotlin uses String’s extension functions such as .toLong() and toLongOrNull() to make things easier. Let’s dive into their implementation.
- For Long, use this:
public inline fun String.toLong(): Long = java.lang.Long.parseLong(this)
As you can see, internally, it also calls the Long.parseLong(string) Java static method, and it is similar to the other data types.
- For Short, it's the following:
public inline fun String.toShort(): Short = java.lang.Short.parseShort(this)
- Use this for Int:
public inline fun String.toInt(): Int = java.lang.Integer.parseInt(this)
- For parsing with Radix, use the following:
public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))
The checkRadix method checks whether the given [radix] is valid radix for string to number and number to string conversion.