In some code I’m developing, I need to dynamically check interface conformance of Enum classes, given their Java Class values.
Here is what I have: an interface (that I define), several enum classes (defined by consumers of my API, hopefully implementing my interface plus further requirements), and their Java Class references:
interface MyEnumInterface {
val foo: String
}
enum class SomeEnum(
override val foo: String
): MyEnumInterface {
ITEM("bar")
}
val someEnumClass = SomeEnum::class.java
First of all I check that the class implements my interface:
require(someEnumClass.kotlin.isSubclassOf(MyEnumInterface::class))
That being checked, I need to assert some further requirements on all items of the enum. Here I came up with two ways of writing the code:
require((someEnumClass.enumConstants as Array<MyEnumInterface>).all { item ->
// warning: unchecked cast: ^^^^^^^^^^^^^^^^^^^^^^^^^
item.foo == "bar"
})
require(someEnumClass.enumConstants.all {
val item = it as MyEnumInterface
// no warning!?
item.foo == "bar"
})
The interesting part is that the first style gives a compiler warning, while the second one does not. Is the second style safer, for any reason? (I can’t see how.) Should I prefer it, just because it does not result in a warning? Should I report this missing warning to be fixed in the compiler?
Finally, is there a better way to write any part of these checks?