1. Overview

In this quick tutorial, we’re going to get familiar with a couple of ways to convert String to Int in Kotlin.

2. String to Int Conversion

In its simplest scenario, we can use the toInt() extension function to convert a String to its corresponding Int value. When the String contains valid numeric content, everything should work smoothly:

val intValue = "42".toInt()
assertEquals(42, intValue)

On the other hand, if the String does not contain valid numeric data, the same function will throw a NumberFormatException:

assertThrows<NumberFormatException> { "0x2a".toInt() }
assertThrows<NumberFormatException> { "2.5".toInt() }
assertThrows<NumberFormatException> { "2.5 inch".toInt() }
assertThrows<NumberFormatException> { "invalid".toInt() }

As shown above, those Strings are not valid integers, hence the exceptions.

If we don’t like exceptions, we can use toIntOrNull() extension function, which returns null for invalid integers:

assertNull("invalid".toIntOrNull())
assertEquals(42, "42".toIntOrNull())

So, when the String contains valid integral values, then the toIntOrNull() behaves similarly to toInt(). On the other hand, for invalid integral values, it simply eats the exception and returns null instead.

2.1. Radix Conversions

Sometimes a String contains an integer value in a radix (or base) other than 10. In order to convert such values, we can pass the radix as the second argument:

val intValue = "2a".toInt(16)
assertEquals(42, intValue)

Here, the “2a” is a valid hexadecimal value, so we’re passing 16 as the radix. Similarly, we can pass a radix to the toIntOrNull() function, as well:

assertEquals(42, "2a".toIntOrNull(16))

2.2. Unsigned Values

*It’s even possible to convert Strings to unsigned integers* Kotlin supports them as of Kotlin 1.3:

assertEquals(42u, "42".toUInt())
assertEquals(42u, "2a".toUInt(16))
assertNull("2a".toUIntOrNull())
assertEquals(42u, "2a".toUIntOrNull(16))

As shown above, the toUInt() and toUIntOrNull() are quite similar to their signed equivalents. As of Kotlin 1.5, unsigned integers are a stable feature. However, if we’re on earlier versions of Kotlin, we have to opt-in with the @ExperimentalUnsignedTypes annotation to use this experimental feature.

3. Conclusion

In this tutorial, we saw how to convert Kotlin Strings to their corresponding Int values.

As usual, all the examples are available over on GitHub.


« 上一篇: Kotlin中过滤列表