0

Let's say I have a class like this :

class User {
    lateinit var firstname: String
    lateinit var lastname: String
    lateinit var age: String
}

Now, I want to populate this class, and use it, like this :

fun main() {
    val user = User()
    user.firstname = "firstname"
    user.lastname = "lastname"
    user.age = "25";
    println("Hello, ${user.firstname} ${user.lastname}, you are ${user.age} !")
}

Output : > Hello, firstname lastname, you are 25 !

In Kotlin, we have some syntactic sugar keyword with, which returns the receiver passed in params and allows us not to repeat the variable name over and over, for example, this will output the same thing and is a bit more pretty :

fun main() {
    val user = User()
    with (user) {
        firstname = "firstname"
        lastname = "lastname"
        age = "25";
        println("Hello, $firstname $lastname, you are $age !")
    }
}

Is there an equivalent to Kotlin's with(receiver: T, block: T.() -> R) function in Dart ?

Mathieu
  • 1,435
  • 3
  • 16
  • 35
  • 1
    See if [this](https://stackoverflow.com/a/52148494/8244632) helps, meant for `let` but you can utilize for your use case. – Lalit Fauzdar Dec 01 '22 at 19:43
  • I saw that, I guess I will use that. I was expecting something already done in the Dart language, not some *trick* I should implement (would be irrelevant in my small case) – Mathieu Dec 01 '22 at 19:45
  • 1
    There's nothing, in Dart, exactly like the scope functions of Kotlin, at least for now, AFAICT. So, either you can create functions providing similar functionality but not in the receiver manner of Kotlin or you can use an example as provided in the answer. – Lalit Fauzdar Dec 01 '22 at 19:47
  • Thank you for your help, I am trying it ! – Mathieu Dec 01 '22 at 19:52
  • That’s not really the intended use of `with`. `apply` is more appropriate since you are configuring an object without producing a result. I don’t know Dart but from a brief look at the docs, it looks like the idiomatic way to do this is with the cascade operator. `..` – Tenfour04 Dec 02 '22 at 05:26

0 Answers0