官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 镇赉县| 泗洪县| 东乌珠穆沁旗| 康定县| 老河口市| 简阳市| 长葛市| 泗阳县| 灵石县| 百色市| 如皋市| 禹州市| 灵台县| 顺义区| 迁西县| 巫溪县| 潮安县| 湘潭县| 乌拉特前旗| 偃师市| 新化县| 青岛市| 施秉县| 北京市| 静宁县| 连城县| 娱乐| 白河县| 乡城县| 永州市| 翼城县| 宜都市| 安徽省| 通州市| 西乌珠穆沁旗| 和静县| 安义县| 齐齐哈尔市| 宜兴市| 洪洞县| 深水埗区|