Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda