https://kotlinlang.org logo
#announcements
Title
# announcements
k

kevinmost

10/26/2017, 6:31 PM
enumValueOf
x

xkor

10/26/2017, 6:36 PM
this method require type parameter, but I have no it...
k

kevinmost

10/26/2017, 6:41 PM
ah yeah, if you don't know the type at compile-time, that won't work. Why can't you use
java.lang.Enum.valueOf
?
x

xkor

10/26/2017, 6:42 PM
because it also require type parameter(
and it is not compiling
java.lang.Enum.valueOf<Enum<*>>(type.java, value)
k

kevinmost

10/26/2017, 6:49 PM
it's not ideal, but you could define an unsafe Java util method that uses a raw type:
Copy code
@SuppressWarnings("unchecked")
    @Nullable 
    public static Enum<?> enumValueOf(@NonNull Class<Enum> type, @NonNull String name) {
        return Enum.valueOf(type, name);
    }
the problem seems to me to be the enum's self-referencing generic type
that method returns
@NonNull
actually 🙂
x

xkor

10/26/2017, 6:57 PM
I found solution!
type.java.enumConstants.first { it.toString() == value }
k

kevinmost

10/26/2017, 7:01 PM
nice, that seems like a cleaner solution
maybe check
it.name == value
, since that's what
Enum.valueOf
and
enumValueOf
check
x

xkor

10/26/2017, 7:06 PM
in common yes. But in my case toString is better, because I use toString to serialise
3 Views