Search code examples
kotlinkotlin-extension

Not nullable Mutable Map


  • Java : 1.8.0_102
  • Kotlin: 1.0.4

I'm trying to create a map where you can do something like map["key"] += 5 similar to javascript.

Kotlin already has withDefault that solves one part of this, but map's get function still returns a nullable value, so i proceeded to make my own implementation of this inspired by withDefault

interface NonNullableMutableMap<K,V> : MutableMap<K,V> {
  override fun put(key: K, value: V): V
  override fun get(key: K): V
}

fun <K,V> MutableMap<K,V>.withoutNullValues(default: () -> V): NonNullableMutableMap<K, V> {
  return NonNullableMapWrapper(this, default)
}

class NonNullableMapWrapper<K,V>(val map: MutableMap<K,V>, val default: () -> V) : NonNullableMutableMap<K,V> {
  override fun put(key: K, value: V): V = map.put(key, value) ?: default()

  override fun get(key: K): V {
      val value = map.getOrPut(key, default)
      return value
  }
  override val size: Int get() = map.size

  override fun containsKey(key: K): Boolean = map.containsKey(key)

  override fun containsValue(value: V): Boolean = map.containsValue(value)

  override fun isEmpty(): Boolean = map.isEmpty()

  override val entries: MutableSet<MutableMap.MutableEntry<K, V>> get() = map.entries
  override val keys: MutableSet<K> get() = map.keys
  override val values: MutableCollection<V> get() = map.values

  override fun clear() {
      map.clear()
  }

  override fun putAll(from: Map<out K, V>) {
    map.putAll(from)
  }

  override fun remove(key: K): V {
    return map.remove(key) ?: default()
  }
}

I created the following unit test to test it

class NonNullableMapTest {

  @Test
  fun notNullableTest() {
      val map = HashMap<String, Long>().withoutNullValues { 0 }
      map["first"] += 10L
      map["second"] -= 10L
      assertThat(map["first"]).isEqualTo(10L)
      assertThat(map["second"]).isEqualTo(-10L)
      assertThat(map["third"]).isEqualTo(0L)
  }
}

But i'm getting the following error when i run the test:

tried to access method kotlin.collections.MapsKt__MapsJVMKt.set(Ljava/util/Map;Ljava/lang/Object;Ljava/lang/Object;)V from class foo.bar.NonNullableMapTest
java.lang.IllegalAccessError: tried to access method kotlin.collections.MapsKt__MapsJVMKt.set(Ljava/util/Map;Ljava/lang/Object;Ljava/lang/Object;)V from class foo.bar.NonNullableMapTest

Any idea how to resolve this issue?


Solution

  • This looks like a bug to me. I recommend reporting it at Kotlin (KT) | YouTrack.

    One way to workaround it is by explicitly defining set on your NonNullableMutableMap interface. e.g.:

    interface NonNullableMutableMap<K, V> : MutableMap<K, V> {
        override fun put(key: K, value: V): V
        override fun get(key: K): V
        operator fun set(key: K, value: V) {
            put(key, value)
        }
    }