Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String array to Int array in Kotlin?

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] 
like image 866
saidfagan Avatar asked Aug 22 '17 16:08

saidfagan


People also ask

How do I convert a string to an int in Kotlin?

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.

Is string an array in Kotlin?

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.


2 Answers

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().

like image 140
hotkey Avatar answered Oct 07 '22 02:10

hotkey


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() 
like image 33
s1m0nw1 Avatar answered Oct 07 '22 02:10

s1m0nw1