I am trying learn Kotlin.
I have an array: [1,2,3,4,5]
How can I print the squares of each of the numbers in the 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 am not sure how to do this in Kotlin
IntArray is a class in Kotlin representing the array of elements. Each instance of this class is represented as an integer array. To the constructor of this class you need to pass the number of elements you need in the array (size).
To create an array, use the function arrayOf() and pass the item values to it, so that arrayOf(1, 2, 3) creates an array [1, 2, 3] .
In Kotlin, arrays can be created using the function arrayOf() or using an Array constructor. Arrays are stored in a sequence as per the memory location is concerned. All the elements in an array can be accessed using their index. Arrays are mutable in nature.
To get size of Array in Kotlin, read the size property of this Array object. size property returns number of elements in this Array. We can also use count() function of the Array class to get the size. We will go through an example to get the size of the Array using count() function.
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]
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