Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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();
 }
over 4 years ago · Santiago Trujillo Report

0

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)
}
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!