What is Kotlin equivalent for Java "assign and check"?

4ntoine :

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?

Ricky Mo :

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();
 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72130&siteId=1