3

I have the following interface in kotlin, not modifiable because it's defined in a third party library. And I would like to override the generic method using a type parameter of the subclass:

interface Factory {
    fun <T> create(modelClass: Class<T>): T
}


// The naive solution doesn't compile :  "Class is not abstract and does not implement abstract member":
class ConcreteFactory1 <T> (val creator: () -> T) : Factory {
    override fun create(modelClass: Class<T>): T {
        return creator()
    }
}


// If we introduce a second type parameter, it compiles, but generates a "Unchecked Cast" warning:
class ConcreteFactory2 <T> (val creator: () -> T) : Factory {
    override fun <T2> create(modelClass: Class<T2>): T2 {
        return creator() as T2
    }
}

Is there a way to achieve this without compilation warning ?

1 Answer 1

1

It depends. That interface requires that you're able to handle any possbile Class<T> and your implementation doesn't.

So the question is what do you want to do when create is called with a type which is not the one your ConcreteFactory2 can create?

If the only thing you want is not to see the unchecked cast you can do this:

class ConcreteFactory2 <T> (val creator: () -> T) : Factory {
    override fun <T2> create(modelClass: Class<T2>): T2 {
        return creator() as? T2 ?: throw IllegalArgumentException("unsupported type")
    }
}

But whether that is an acceptable implementation of that interface really depends on how is that used.

Sign up to request clarification or add additional context in comments.

4 Comments

Warning is still there with this solution Unchecked cast: T to T2
Since the type isn't reified, I don't think a safe cast operator will work. You'll just get a ClassCastException when it returns instead of the more informative IllegalArgumentException. But this approach could work if you have a KClass property in the constructor so the type can be reified and checked for real.
I'm wrong. That would only reify T, not T2. There's no way to reify T2, so you can't safely cast it.
whoops, sorry didn't try that out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.