How can I square each element of an integer array in Kotlin

I am trying to learn Kotlin.

I have an array: [1,2,3,4,5]

How can I print the squares of each of the numbers in an array?

For example, in Python, I could just do:

array = [1,2,3,4,5]
print(" ".join (str(n*n) for n in array))

But I'm not sure how to do this in Kotlin

+4
source share
2 answers

You can use map :

val array = arrayOf(1,2,3,4,5)
println(array.map { n: Int -> n * n }) 

Conclusion:

[1, 4, 9, 16, 25]
+7
source

In Kotlin you use joinToString:

val array = arrayOf(1, 2, 3, 4, 5)
println(array.joinToString(separator = " ") { n -> "${n * n}" })

You can also use joinToto connect directly to the buffer (e.g. System.out) and avoid the intermediate String:

array.joinTo(System.out, separator = " ") { n -> "${n * n}" }
+3
source

Source: https://habr.com/ru/post/1679004/


All Articles