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

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.

主站蜘蛛池模板: 嘉义市| 灌云县| 年辖:市辖区| 铜鼓县| 友谊县| 文水县| 宝兴县| 海宁市| 剑阁县| 泗洪县| 白玉县| 瑞安市| 东平县| 唐河县| 武鸣县| 长海县| 延津县| 临城县| 临桂县| 伊通| 东至县| 凤庆县| 偏关县| 澄江县| 安陆市| 广安市| 绵竹市| 叶城县| 榆中县| 同心县| 金塔县| 恭城| 遵化市| 大同县| 海城市| 河间市| 开鲁县| 阿拉善盟| 沁源县| 渭源县| 滨海县|