Kotlin, when to delegate a card?

I checked the documentation on delegate , and I found that the provided map delegation type exists:

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

But I could not understand what is the difference between a version without a delegate , for example:

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

And what is the common use for the delegate by map ?

Thanks!

+5
source share
1 answer

The difference is that in the first delegate example, all you have to do is put the map in the constructor and do it.

 val user = MutableUser(mutableMapOf( "name" to "John Doe", "age" to 25 )) println(user.name) // Prints "John Doe" println(user.age) // Prints 25 

But in order for this to be the same in the second example, you need to implement the initialization of the properties on the 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 a JSON parser.

+5
source

Source: https://habr.com/ru/post/1262726/


All Articles