Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

thanks in advanced

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading