Enhancing a class

Your boss—sorry, scrum master—came to you yesterday with an urgent requirement. From now on, all map data structures in your system are to become HappyMaps

What, you don't know what HappyMaps are? They are the hottest stuff going around right now. They are just like the regular HashMap, but when you override an existing value, they print the following output:

Yay! Very useful

So, what you do is type the following code in your editor:

class HappyMap<K, V>: HashMap<K, V>() {
override fun put(key: K, value: V): V? {
return super.put(key, value).apply {
this?.let {
println("Yay! $key")
}
}
}
}

We've seen apply() already when we discussed the Builder design pattern in the previous chapter and this?.let { ... }  is a nicer way of saying if (this != null) { ... }.

We can test our solution using the following code:

fun main(args : Array<String>) {
val happy = HappyMap<String, String>()
happy["one"] = "one"
happy["two"] = "two"
happy["two"] = "three"
}

The preceding code prints the following output as expected:

Yay! two

That was the only overridden key.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.251.206