Kotlin generic type inference - inheritance

Viewed 106

I have some abstract with generic type:

interface Abstract<T> {
    val dataHolder: T
}

class AbstractImplA : Abstract<String> { 
    override val dataHolder = "Test"
}

class AbstractImplB : Abstract<Int> {
    override val dataHolder = 1
}

Now I want to create open class that persist this data:

open class Base<T>(private val abstract: Abstract<T>) {

    val data : T get() = abstract.dataHolder

    // ...
}

now for child class I have to explicitly specifiy generic type of Abstract:

class ClassA : Base<String>(AbstractImplA()) {

    fun foo() {
        assertEquals("Test", data)
    }
}

class ClassB : Base<Int>(AbstractImplB()) {

    fun foo() {
        assertEquals(1, data)
    }
}

I wander if Kotlin can infere this type.

Passing wrong generic type causes Type mismatch error ex. class ClassB : Base<Boolean>(AbstractImplB())

Can I somehow write it like this?:

class ClassB : Base(AbstractImplB()) {

    fun foo() {
        assertEquals(1, data)
    }
}
0 Answers
Related