Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin, when to delegate by map?

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!

like image 808
MewX Avatar asked Jan 13 '17 07:01

MewX


1 Answers

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.

  • Storing Properties in a Map
like image 194
Januson Avatar answered Oct 30 '22 18:10

Januson