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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With