Kotlin Programming Cookbook
上QQ阅读APP看书,第一时间看更新

Converting with special radix

All the preceding examples use the base (radix) 10. There are cases when we wish to convert a String to Long but using another base. Both string.toLong() and string.toLongOrNull() can receive a custom radix to be used in the conversion. Let's take a look at its implementation:

  • string.toLong(radix):
    • This parses the string as a [Long] number and returns the result
    • @throws NumberFormatException if the string is not a valid representation of a number
    • @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion
  • string.toLongOrNull(radix):
    • This parses the string as a [Long] number and returns the result or null if the string is not a valid representation of a number
    • @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion