So, we learned how to use standard delegates, but Kotlin has to offer more with delegation. The map delegation is among those awesome features that comes with delegation. So, what is it? It is the freedom of passing a map as a single parameter instead of numbers of parameters in a function/class constructor. Let's have a look. The following is a program applying map delegation:
data class Book (val delegate:Map<String,Any?>) { val name:String by delegate val authors:String by delegate val pageCount:Int by delegate val publicationDate:Date by delegate val publisher:String by delegate } fun main(args: Array<String>) { val map1 = mapOf( Pair("name","Reactive Programming in Kotlin"), Pair("authors","Rivu Chakraborty"), Pair("pageCount",400), Pair("publicationDate",SimpleDateFormat("yyyy/mm/dd").parse("2017/12/05")), Pair("publisher","Packt") ) val map2 = mapOf( "name" to "Kotlin Blueprints", "authors" to "Ashish Belagali, Hardik Trivedi, Akshay Chordiya", "pageCount" to 250, "publicationDate" to SimpleDateFormat("yyyy/mm/dd").parse("2017/12/05"), "publisher" to "Packt" ) val book1 = Book(map1) val book2 = Book(map2) println("Book1 $book1 nBook2 $book2") }
The program is simple enough; we defined a Book data class, and in the constructor, instead of taking all member values one by one, we took a map and then delegated all to the map delegate.
One thing to be cautious here is to mention all member variables in the map, and the key name should exactly match the property name.
Here is the output:
Simple enough, isn't it? Yes, delegations are that much powerful. But are you curious about what will happen if we skip mentioning any of the properties in the map? It will simply avoid the properties you skipped, and if you explicitly try to access them, then it'll throw an exception—java.util.NoSuchElementException.