15

I checked the documentation on delegate, and I found there was a provided delegate type map:

class MutableUser(val map: MutableMap<String, Any?>) {
    var name: String by map
    var age: Int     by map
}

But I couldn't figure out what's the difference between the version without delegate, like this:

class MutableUser(val map: MutableMap<String, Any?>) {
    var name: String
    var age: Int
}

And what's the common usage for the delegate by map?

Thanks!

1 Answer 1

14

Difference is that in the first example with delegate, all you have to do is to put map to the constructor and done.

val user = MutableUser(mutableMapOf(
        "name" to "John Doe",
        "age"  to 25
))

println(user.name) // Prints "John Doe"
println(user.age)  // Prints 25

But for this to work the same with your second example, you have to implement initialization of properties from map yourself.

class MutableUser(val map: MutableMap<String, Any?>) {
    var name: String
    var age: Int

    init {
        name = map["name"].toString()
        age = map["age"].toString().toInt()
    }
}

One common use case would be implementing a JSON parser.

1
  • 6
    The other way around works too - when you modify name, the map is modified accordingly
    – voddan
    Jan 13, 2017 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.