Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda