Kotlin has many shorthands and interesting features. So, I wonder if there is some fast and short way of converting array of string to array of integers. Similar to this code in Python:
results = [int(i) for i in results]
Kotlin convert String to InttoInt() to parse the string to an Int , NumberFormatException is thrown if the string is not a valid representation of an Integer. toIntOrNull() to convert the string to an Int , return a null if the string is not a valid representation of an Integer.
Kotlin StringThe String class represents an array of char types. Strings are immutable which means the length and elements cannot be changed after their creation. Unlike Java, Kotlin does not require a new keyword to instantiate an object of a String class.
You can use .map { ... }
with .toInt()
or .toIntOrNull()
:
val result = strings.map { it.toInt() }
Only the result is not an array but a list. It is preferable to use lists over arrays in non-performance-critical code, see the differences.
If you need an array, add .toTypedArray()
or .toIntArray()
.
I'd use something simple like
val strings = arrayOf("1", "2", "3") val ints = ints.map { it.toInt() }.toTypedArray()
Alternatively, if you're into extensions:
fun Array<String>.asInts() = this.map { it.toInt() }.toTypedArray() strings.asInts()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With