如何在Kotlin中将String数组转换为Int数组?

如何在Kotlin中将String数组转换为Int数组?

问题描述:

科特林(Kotlin)具有许多速记和有趣的功能.因此,我想知道是否存在将字符串数组转换为整数数组的快捷方式.类似于Python中的以下代码:

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]

您可以使用 .map { ... } .toInt() .toIntOrNull() :

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.

如果需要数组,请添加 .toTypedArray() .toIntArray() .

If you need an array, add .toTypedArray() or .toIntArray().