1

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

3
  • Am trying to make the equal part dynamic. Are you saying you want to create these variables like first, second dynamically? Commented Jun 20, 2022 at 10:10
  • @Arpit Shukla Exactly Commented Jun 20, 2022 at 10:16
  • Creating variables at run time isn't possible. Why do you need to do that? Can you share an example? Commented Jun 20, 2022 at 10:18

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm not sure about your example Kotlin code. It seems unrelated to what you do in Python.
I have edited my question to address this concern
I'm still not exactly sure what you mean. You first speak about creating an array/list from another list and then you jump into unpacking/destructuring into first/second, which is pretty unrelated thing. If you just wanted to use both of these features at the same time then see my updated answer.
2

Try this out:

// === KOTLIN

var mylist = listOf(1, 2)

            
val result = mylist.map { it * 2 }

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.