Andrew Ebling
05/14/2021, 10:21 AMenum 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:
interface MyEnumInterface {}
enum class MyEnumClass: MyEnumInterface { ... }
var myTreeMap: TreeMap<MyEnumInterface, (() -> (Unit))> = TreeMap()
however when I call this method, passing an instance of `MyEnumClass`:
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?diesieben07
05/14/2021, 11:03 AMMyEnumInterface
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
Andrew Ebling
05/14/2021, 11:08 AMdiesieben07
05/14/2021, 11:08 AMTreeMap
code?Andrew Ebling
05/14/2021, 11:10 AMat 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)
diesieben07
05/14/2021, 11:11 AMenum
?Andrew Ebling
05/14/2021, 11:11 AMdiesieben07
05/14/2021, 11:11 AMComparator
that knows how to compare all possible keysAndrew Ebling
05/14/2021, 11:11 AMkqr
05/14/2021, 1:37 PM