9

I'm trying to make mapOf() returns EnumMap if K is Enum. However, the error occurs at first type variable of Enum (K)

Code:

@kotlin.internal.InlineOnly
public inline fun <reified K, V> mapOf(): Map<K, V> =
    if (K::class.java.isEnum) EnumMap<K, V>(K::class.java)
    else emptyMap()

Error:

Type argument is not within its bounds.
Expected: Enum<K!>!
Found: K

I'd like to give objects other than Enum too, so reified K: Enum<*> can't be a solution.

3
  • I think the issue is that K::class.java.isEnum doesn't imply K extends Enum<K>
    – jrtapsell
    Apr 12, 2018 at 13:32
  • How would you like to use it? Your logic here is incorrect, because only solution to make your code correct is to add reified K : Enum<K>? as you've said. But as you can see what kind of object could match this condition? ;) Please share with us your use case.
    – muminers
    Apr 12, 2018 at 13:36
  • @muminers You'd use it like you normally would: mapOf<String, Int>(), mapOf<MyEnum, String>(). The latter would instantiate an optimized EnumMap. Apr 12, 2018 at 15:06

2 Answers 2

4

Evil cheating using type erasure:

import java.util.concurrent.TimeUnit // you can use any other enum as well

@Suppress("UNCHECKED_CAST")
public inline fun <reified K, V> mapOf(): Map<K, V> =
    if (K::class.java.isEnum) 
        EnumMap<TimeUnit, V>(K::class.java as Class<TimeUnit>) as Map<K, V>
    else emptyMap()

At runtime this is effectively just EnumMap(K::class.java), all casts disappear.

1
  • Hey nice! Interesting solution :) Apr 12, 2018 at 19:09
3

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.

1
  • I think my way is cleaner :) Apr 12, 2018 at 18:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.