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

203
Views
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 answers
Answer question

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 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!