In Java sometimes i write the code as follows:
String obj = null;
while ((obj = getObject()) != null) {
// do smth with obj
}
In Kotlin compile-time error is shown:
Assignments are not expressions, and only expressions are allowed in this context
What's the best equivalent in Kotlin?
I would rather give up fanciness and do it the old-school way, which is instead most intuitive.
var obj = getObject();
while (obj != null) {
// do smth with obj
obj = getObject();
}
The simplest ad-hock solution is probably
while(true) {
val obj = getObj() ?: break
}
However special cases are IMO best served by specialized helper functions. For example reading a file line by line can be done with a helper readLines as explained in an answer to a similar question:
reader.forEachLine {
println(it)
}
In cases you just want to replace while ((x = y.someFunction()) != null) you may use the following instead:
generateSequence { y.someFunction() }
.forEach { x -> /* what you did in your while */ }
generateSequence will extract you all the values one by one until the first null is reached. You may replace the .forEach with a reduce or fold (or anything else that seems appropriate ;-)) if you want to keep the last value or sum up the values to something else.
If you need to check against something else, you may just add something like takeIf, e.g.:
generateSequence { y.someFunction().takeIf { /* yourCondition... */ } }
basically just repeating what I also mentioned here.