'What would be an idiomatic way in kotlin to generate a list of items by calling a function?

Let's say there is a function that returns a single nullable return value. For instance:

fun getItem(): String?

I'd like to create a new list of items by calling this function until it returns null.

My idea would be to write an iterator that iterates the return value until it's null. However, is there a more elegant or idiomatic way to approach this issue?



Solution 1:[1]

Not sure about what would be idiomatic tbh, but you can use a simple while(true) to achieve it.

val list = mutableListOf<String>()

while (true) getItem()?.let { list += it } ?: break

That basically translates to:

while true (infinite loop).
if getItem() is not null, add it to the list.
if getItem() is null, then break the loop. 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex.T