Search code examples
kotlin

How to use withDefault wrappers?


I want to use MutableMap with defaults:

val myMap = mutableMapOf<String, Set<String>>().withDefault { mutableSetOf() }

but I can't use getOrImplicitDefault method because withDefault returns MutableMap<String, Set<String>> type. Moreover, I can't cast to MutableMapWithDefault interface because this is a private interface.

I can't use get method either because it returns a nullable type. It is ok because this is a method on the MutableMap interface (moreover it doesn't call defaultValue callback for take default value).

Seems like this functionality is not correctly implemented in Kotlin, or I am using it wrong. So, how do I use withDefault wrappers correctly?


Solution

  • As of Kotlin 1.0 a wrapper returned by withDefault is only usable in property delegation use cases.

    val map = mutableMapOf<String, Set<String>>().withDefault { mutableSetOf() }
    
    var property: Set<String> by map // returns empty set by default