How can I square each item of an integer array in Kotlin
You could use map:
val array = arrayOf(1, 2, 3, 4, 5)
println(array.map { n: Int -> n * n })
Output:
[1, 4, 9, 16, 25]
In Kotlin you use joinToString
:
val array = arrayOf(1, 2, 3, 4, 5)
println(array.joinToString(separator = " ") { n -> "${n * n}" })
You can also use joinTo
to join directly to a buffer (e.g. System.out
) and avoid the intermediate String
:
array.joinTo(System.out, separator = " ") { n -> "${n * n}" }