Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

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

like image 271
KotlinNewbie Avatar asked Jun 12 '17 00:06

KotlinNewbie


People also ask

What is IntArray 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).

How do you create an array of integers in Kotlin?

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] .

How do you initialize an array with values in Kotlin?

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.

How does Kotlin define array size?

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.


1 Answers

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]
like image 168
Sash Sinha Avatar answered Oct 12 '22 01:10

Sash Sinha