Type for a class implementing an interface?


#1

This is probably something very very easy, but I am struggling to figure it out.

For the given parameter declaration (appears in a constructor)

val keyFunction: Class<*>

How do I make the type constraint more specific, ie. keyFunction is a class that implements an interface ValueGenerator<*> or ValueGenerator<String> (instead of just Class<*>)

I tried

val keyFunction: Class<? extends ValueGenerator<*>>

but that will not compile


#2

Only types and functions can have generic parameter declarations, so you need to use your property inside a type or function. Here are similar examples using a class:

class RunnableClient<T: Runnable>(val  runnableImplementationClass: Class<T>)

Or as a member:

class RunnableClient<T: Runnable> {
    val  runnableImplementationClass: Class<T>
    
    init {
        // Initialize "runnableImplementationClass" here
    }
}

#3

Amongst genericity and being able to specify that the particular class is
implementing an interface, the latter is of a much higher priority. So,
even if I can find a way to declare, val keyFunction: Class<? extends ValueGenerator<*>>, that would be wonderful. But I can’t find a way to do
that.

Not sure if that helps, but the specific issue I am dealing with is being
able to deserialise a json/yaml file into kotlin where the particular field
(keyFunction) refers to a className which implements a required interface.
So once the object containing the field gets deserialised, I can in a type
safe way use the class to create an instant and invoke functions on the
interface.


#4

Kotlin does not have wildcard types (?). The most direct way to translate your Java syntax to Kotlin would be Class<out ValueGenerator<*>>.


#5

That worked. Thank you.