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
CodePudding user response:
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.
CodePudding user response:
Try this out:
// === KOTLIN
var mylist = listOf(1, 2)
val result = mylist.map { it * 2 }
println(result)
// output: [ 2,4 ]