Provide the way to specify implicit default for a readonly or mutable map.

Refactor: rename default key and value providers.
This commit is contained in:
Ilya Gorbunov
2015-06-17 20:54:25 +03:00
parent d137a83471
commit 5306e88425
5 changed files with 139 additions and 42 deletions
@@ -3,6 +3,7 @@ package test.collections
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.test.fails
import org.junit.Test as test
class MapTest {
@@ -21,6 +22,27 @@ class MapTest {
assertEquals(null, c)
}
test fun getOrImplicitDefault() {
val data: MutableMap<String, Int> = hashMapOf("bar" to 1)
assertTrue(fails { data.getOrImplicitDefault("foo") } is KeyMissingException)
assertEquals(1, data.getOrImplicitDefault("bar"))
val mutableWithDefault = data.withDefault { 42 }
assertEquals(42, mutableWithDefault.getOrImplicitDefault("foo"))
// verify that it is wrapper
mutableWithDefault["bar"] = 2
assertEquals(2, data["bar"])
data["bar"] = 3
assertEquals(3, mutableWithDefault["bar"])
val readonlyWithDefault = (data as Map<String, Int>).withDefault { it.length() }
assertEquals(4, readonlyWithDefault.getOrImplicitDefault("loop"))
val withReplacedDefault = readonlyWithDefault.withDefault { 42 }
assertEquals(42, withReplacedDefault.getOrImplicitDefault("loop"))
}
test fun getOrPut() {
val data = hashMapOf<String, Int>()
val a = data.getOrPut("foo") { 2 }