Search code examples
androidlistloopskotlinparameter-passing

Create a list os Kotlin with de result of a repeated function


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.


Solution

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