Pavlo Ostasha
Pavlo Ostasha

Reputation: 16719

Kotlin `apply()` method analog in Dart

I would like to be able to do something like apply() from Kotlin in Dart. For example in Kotlin

var userDetails: UserDetails = userRepo.getUser().apply{
    //here 'this' is UserDetails so all the further calls are made in that context
    name = "Name"
    email = "[email protected]"
    callSomeInnerMethodOfUserDetails()
};

Is there some similar method or way to do it in Dart language?

I want to know whether there are some things in standard library or language itself, rather than my own generic closure extension for such a purpose?

Thanks.

Upvotes: 9

Views: 1900

Answers (1)

Pavlo Ostasha
Pavlo Ostasha

Reputation: 16719

While there is no exact analog I stumbled upon a peculiar operator called Cascade notation that does similar job.

The given example will look something like:

UserDetails userDetails = userRepo.getUser()
    ..name = 'Name'
    ..email = '[email protected]'
    ..callSomeInnerMethodOfUserDetails();

You can also do a nested cascade also

UserDetails otherUserDetails = userRepo.getUser()
    ..name = (userRepo.getUser()
              ..firstName= "Other Name"
              ..assignFirstNameAndSurnameToNameField()).name
    ..email = "otherEmail"
    ..callSomeInnerMethodOfUserDetails();

Hope it helps.

Upvotes: 11

Related Questions