I'm trying to write something like this:
var classList = ArrayList<Class<Any>>()
init {
classList.add(ClassA::class.java)
classList.add(ClassB::class.java)
}
That gets me errors like:
Type inference failed. Expected type mismatch: inferred type is Class<ClassA> but Class<Any> was expected
I can get rid of the error by doing an explicit cast:
domainClasses.add(NameIdMapping::class.java as Class<Any>)
That gets me an "unchecked cast" warning. Is that the best I can do? How to do this cleanly?
The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.
In Kotlin we use a single colon character ( : ) instead of the Java extends keyword to extend a class or implement an interface. We can then create an object of type Programmer and call methods on it—either in its own class or the superclass (base class).
You extend a class when you want the new class to have all the same features of the original, and something more. The child class may then either add new functionalities, or override some funcionalities of the parent class.
You just use typeName of java. lang. Class<T> instead of the qualifiedName of KCLass<T> (more Kotlin-ish) as I've shown in my answer stackoverflow.com/a/45165263/1788806 which was the previously chosen one. @WilliMentzel Your answer is perfect and idiomatic.
Use an out
-projection: ArrayList<Class<out Any>>
, this is mostly equivalent to a Java ? extends
wildcard.
See: Variance in the language reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With