Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Kotlin equivalent for Java "assign and check"? [duplicate]

Tags:

java

kotlin

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?

like image 996
4ntoine Avatar asked Dec 10 '22 03:12

4ntoine


2 Answers

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();
 }
like image 174
Ricky Mo Avatar answered Feb 20 '23 06:02

Ricky Mo


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)
}
like image 42
voddan Avatar answered Feb 20 '23 08:02

voddan