Kaita John
Kaita John

Reputation: 1109

How to initiate array items using for loop in Kotlin

Python allows programmers to perform such an operation:

mylist = [1, 2]
items = [value * 2 for value in namelist]

How can I achieve the same using Kotlin, I want to pass values multiplied by 2 from mylist into the array below:

val mylist = mutableListOf(1, 2)
val (first, second) = arrayOf( )

Kotlin allows us to to declare and initiate variables with one liners as below

val (first, second) = arrayOf(1, 2) that way you can call first or second as a variable. Am trying to make the equal part dynamic

Upvotes: 1

Views: 738

Answers (2)

broot
broot

Reputation: 28312

Equivalent of the above Python code in Kotlin is:

val mylist = listOf(1, 2)
val items = mylist.map { it * 2 }

If you need to assign resulting doubled values to first and second, then do it exactly as you did:

val (first, second) = mylist.map { it * 2 }

You need to be sure myList contains at least 2 items.

Upvotes: 2

Iqbal Hussain
Iqbal Hussain

Reputation: 1105

Try this out:

// === KOTLIN

var mylist = listOf(1, 2)

            
val result = mylist.map { it * 2 }

println(result)
// output: [ 2,4 ] 

Upvotes: 2

Related Questions