I try to get multiple results from a folding operation on a list of characters and use a destructuring assignment to both values to their own variables afterwards. But this seems to result in an exception by the kotlin compiler:
java.lang.UnsupportedOperationException: Don't know how to generate outer expression for class <closure-Test$1>
Strangely (to me) without the destructuring, this works as intended. Here is an example:
val fstSec = "fst"
val (fst, snd) = "this is a test for folding to pair"
.toCharArray()
.fold(Pair(0, 0), { sumPair, char ->
when (fstSec) {
"fst" -> Pair(sumPair.first + char.toInt()*2, sumPair.second + char.toInt())
"snd" -> Pair(sumPair.first + char.toInt(), sumPair.second + char.toInt()*2)
else -> throw RuntimeException("exception")
}
})
println("( $fst , $snd )")
This results in the exception.
val fstSec = "fst"
val pair = "this is a test for folding to pair"
.toCharArray()
.fold(Pair(0, 0), { sumPair, char ->
when (fstSec) {
"fst" -> Pair(sumPair.first + char.toInt()*2, sumPair.second + char.toInt())
"snd" -> Pair(sumPair.first + char.toInt(), sumPair.second + char.toInt()*2)
else -> throw RuntimeException("exception")
}
})
println("( ${pair.first} , ${pair.second} )")
This one works as expected, and the only thing I removed was the destructuring. Strangely, if I remove the inner when (and replace it by a Pair constructor only), the code works both times.
Thanks in advance.