Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to express `Class<? extends Any>`

Tags:

kotlin

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?

like image 816
jingx Avatar asked Nov 03 '17 19:11

jingx


People also ask

How to extend a function in Java?

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.

How do I extend a class in Kotlin?

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).

When should you extend a 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.

How do you get the type of variable in Kotlin?

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.


1 Answers

Use an out-projection: ArrayList<Class<out Any>>, this is mostly equivalent to a Java ? extends wildcard.

See: Variance in the language reference.

like image 86
hotkey Avatar answered Oct 19 '22 20:10

hotkey