How do I make a Kotlin list mutable, add items, and then iterate over the resulting immutable list?

115 Views Asked by At

Essentially I need to start with an immutable list of a few items, convert it to a mutable list and add a few items, and then iterate over it with firstOrNull. Here's my scratch file:

val immutableStarter = listOf(1, 2, 3)

val mutable = immutableStarter.toMutableList()
mutable.add(4)
mutable.addAll(listOf(5, 6, 7))
mutable.add(8)

println(mutable)

val result = mutable.firstOrNull { item ->
    println("Checking Item $item")
    item > 7
} ?: 0

println(result)

The println(mutable) call correctly prints the list with all eight items. However, it seems the firstOrNull operation is only running on the first three items in the list. I only get the "Checking Item $item" output three times. If I add a fourth item to the immutableStarter it checks four times. So the best I can gather, for some reason, it's only iterating over the items in the initial, immutable starting list.

If I wrap lines 10-15 in a try/catch or with run, I get the output I would expect - a "Checking Item $item" printout for each of the 8 items in the list.

Why isn't this working as I have it written, and what is it about wrapping the firstOrNull call in a try/catch or run that makes it work?

================================================

EDIT: Someone asked for the output of my scratch file. Here it is:

Checking Item 1
Checking Item 2
Checking Item 3
val immutableStarter: List<Int>

val mutable: MutableList<Int>
true
true
true

[1, 2, 3, 4, 5, 6, 7, 8]


val result: Int


0

It looks like it may be an issue with how scratch files are evaluated - it looks like IntelliJ may be attempting to evaluate the scratch file asynchronously. Toggling the Use REPL checkbox at the top of IntelliJ, for example, gives me the output I'd expect:

res2: kotlin.Boolean = true
res3: kotlin.Boolean = true
res4: kotlin.Boolean = true

[1, 2, 3, 4, 5, 6, 7, 8]



Checking Item 1
Checking Item 2
Checking Item 3
Checking Item 4
Checking Item 5
Checking Item 6
Checking Item 7
Checking Item 8

8
0

There are 0 best solutions below