jingx
jingx

Reputation: 4024

How to express `Class<? extends Any>`

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?

Upvotes: 7

Views: 2042

Answers (1)

hotkey
hotkey

Reputation: 148169

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

See: Variance in the language reference.

Upvotes: 10

Related Questions