Hi. Does anyone know how to cast generic type? I'm...
# announcements
y
Hi. Does anyone know how to cast generic type? I'm trying to make mapOf() returns EnumMap if K is Enum. An error occurs from this code.
Copy code
@kotlin.internal.InlineOnly
public inline fun <reified K: Any, V> mapOf(): Map<K, V> =
    if (K::class.java.isEnum) EnumMap<K, V>(K::class.java)
    else emptyMap()
Copy code
Type argument is not within its bounds.
Expected: Enum<K!>!
Found: K
k
I think you'll have to cast it yourself
K::class.java
as
Class<Enum<K>>
y
Thanks for replying. The error occurs on here: EnumMap<*K*, V>
This code is impossible because the variable (
K::class.java
) must be a class of first type variable (
K
)
EnumMap<K, V>(K::class.java as Class<Enum<K>>)
@karelpeeters Forgot to mention
k
No there are notifications for everyone in a thread, I'm just thinking 🙂
Hmm actually I can't find a way to write it out either...
y
Oh sorry, Thank you for your help!
k
It's frustrating though 😕
Maybe ask on stackexchange?
k
You've got my upvote 🙂
I'd say remove the inlineonly part, that's not really relevant.
y
Thanks. Hmm, but this code works without any error:
Copy code
@kotlin.internal.InlineOnly
public inline fun <reified K: Enum<*>, V> mapOf(): Map<K, V> =
    if (K::class.java.isEnum) EnumMap<K, V>(K::class.java)
    else emptyMap()
k
But that doesn't do anything interesting, right?
The bound on
K
for
EnumMap<K, V>
is now satisfied.
y
Yes, this method receive non-enum objects as arguments. An answerer might think i want to receive only enum objects.