There is no clean way to make this work (afaik), since making K
conform to the bound K extends Enum<K>
(required for EnumMap
) would require the dynamic adding of a bound to K
, which is impossible, since generics are a compile time mechanism.
In java, you would be able to construct the EnumMap
as a raw type, and have it be converted unchecked to the target type (i.e. asserting it is correct). But Kotlin doesn't allow you to do that, since it doesn't allow raw types. I can think of one way to get around this limitation, which is reflection:
val constructor = EnumMap::class.constructors.find {
con ->
con.parameters.size == 1
&& con.parameters[0].type.jvmErasure == Class::class
}!!
inline fun <reified K, V> mapOf(): Map<K, V> =
if (K::class.java.isEnum) constructor.call(K::class.java) as Map<K, V>
else emptyMap()
My Kotlin isn't the best, so there may still be room for improvement. This is a possible workaround though.
mapOf<String, Int>()
,mapOf<MyEnum, String>()
. The latter would instantiate an optimizedEnumMap
.