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

205
Vistas
Kotlin field Assignment via Scope Function (Apply )

What is the difference between two such field assignments? Actually, the first way seems very readable but I come across second way in many code samples.

Is there a special reason?

class Login {

    var grantToken = GrantTokenRequest()
 
    fun schema(schema: String) {
        this.grantToken.schema = schema
    }
    
}




class Login {

    var grantToken = GrantTokenRequest()

    fun schema(schema: String) = apply { this.grantToken.schema = schema }
   

}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

The difference is the return type of the function schema.

The first way returns Unit.

The second way returns the type of what this is in the current scope. In your case the second way will return the Login type, so the instance of this class.

The second approach is just more idiomatic in cases when you are "configuring an object". From Kotlin docs about apply

The common case for apply is the object configuration. Such calls can be read as “apply the following assignments to the object [and return the object itself].”

One reason why the second approach is useful, is because it makes call chaining possible. The general term for this kind of "return this" method chaining is "fluent interface".

val login = Login()
    .schema("...")
    .anotherFunctionOnLoginClass(...)
    .moreCallChaining(...)

An additional note: The this used inside the apply lambda is not needed, because apply already sets this as the Receiver. The code could be simplified to

fun schema(schema: String) = apply { grantToken.schema = schema }
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