https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Andrew Ebling

05/14/2021, 10:21 AM
How do I store instances of an
enum class
implementing an interface in a
TreeMap
such a way that I can set/get set them without throwing a
ClassCastException
? So far I have:
Copy code
interface MyEnumInterface {}

enum class MyEnumClass: MyEnumInterface { ... }
var myTreeMap: TreeMap<MyEnumInterface, (() -> (Unit))> = TreeMap()
however when I call this method, passing an instance of `MyEnumClass`:
Copy code
fun add(howToExecute: () -> (Unit), myEnum: MyEnumInterface) {
   myTreeMap[myEnum] = howToExecute // ClassCastException here
}
... I get a
ClassCastException
. Why does this happen? Why doesn’t it happen when the instance is passed to the add() method? What’s the most appropriate resolution please?
🤔 1
Is this happening because the compiler is only generating code specific to the interface? Can I add some kind of type constraint to the method signature to say “something which implements MyEnumInterface”?
d

diesieben07

05/14/2021, 11:03 AM
I can't reproduce this with the code you've shared: https://pl.kotl.in/7c_jbm5dL Can you provide more details?
One thing that I can imagine happening is that if you use an implementation of
MyEnumInterface
that is not also implementing
Comparable
(which enums do by default).
TreeMap
requires either the keys to implement
Comparable
or otherwise be given an external
Comparator
a

Andrew Ebling

05/14/2021, 11:08 AM
yes - that’s exactly what I’m doing @diesieben07 and I’m at a loss to explain why it works in the playground but not in my production code
this is in an Android app - could that make any difference?
d

diesieben07

05/14/2021, 11:08 AM
I am not too familiar with Android. Can you share what line exactly throws the ClassCastException as well as the message? Does it happen inside
TreeMap
code?
a

Andrew Ebling

05/14/2021, 11:10 AM
Copy code
at java.lang.Enum.compareTo(Enum.java:186)
at java.lang.Enum.compareTo(Enum.java:61)
at java.util.TreeMap.put(TreeMap.java:569)
at com.mycompany.MyObject.add(MyObject.kt:42)
d

diesieben07

05/14/2021, 11:11 AM
So you must have more than one entry in the map. Is it all the same
enum
?
Because if not, obviously they cannot be ordered within each other.
a

Andrew Ebling

05/14/2021, 11:11 AM
ah that will be it
d

diesieben07

05/14/2021, 11:11 AM
then you must provide an external
Comparator
that knows how to compare all possible keys
👍 1
a

Andrew Ebling

05/14/2021, 11:11 AM
many thanks for your help! 👏
k

kqr

05/14/2021, 1:37 PM
@diesieben07 nice