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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With