Home > database >  Create a list os Kotlin with de result of a repeated function
Create a list os Kotlin with de result of a repeated function

Time:01-11

I have a very long method that creates a list with the result of a function that adds two numbers:

private fun Add(one: Int, two:Int) : Int {

 return one   two
}

private val myList = listOf(
 Add(1, 2),
 Add(2, 3),
 Add(3, 4),
 Add(4, 5),
 Add(5, 6),
 Add(6, 7),
 Add(8, 9),
 ...
)

Is there a way in kotlin to create this list without always repeating the name of the "add" function?

I have tried with "with" and "apply" but I think I am not using it correctly.

thanks in advanced

CodePudding user response:

If numbers are randomly generated then you can use some loop to fill the list, e.g.:

private val myList = genarateAndAdd(20)

private fun generateAndAdd(count: Int): List<Int> {
    val list = mutableListOf<Int>()
    repeat(count) {
        list.add(Add(Random.nextInt(), Random.nextInt()))
    }
    return list
}

where count is the size of the myList list.

CodePudding user response:

You can use this:

import java.util.Random

val random = Random()

val myList = (0..<size of your list>).map{add(random.nextInt(), random.nextInt())}
  •  Tags:  
  • Related