poohbar
08/26/2020, 2:49 PMinterface Animal {
val id: String
fun <T: Animal> withSound(sound: String): T
}
data class Dog(
override val id: String
): Animal {
// works
override fun <T : Animal> withSound(sound: String): T {
TODO("Not yet implemented")
}
// does not work
override fun withSound(sound: String): Dog {
TODO("Not yet implemented")
}
}
kqr
08/26/2020, 3:22 PMthanksforallthefish
08/26/2020, 3:27 PMis that the *caller* of the method can decide
.
so, override fun <T : Animal> withSound(sound: String): T
works but it is responsibility of the caller to define T
.
if you want the responsibility to be shifted to the declarator (Dog
in your case), I think interface Animal<T : Animal<T>>
is what you want. but I saw crazy things being done with generics and kotlin generics are much more powerful than java one, somebody more expert might actually make your original solution work as you wantTobias Berger
08/26/2020, 5:28 PMinterface Animal<T: Animal<T>> {
val id: String
fun withSound(sound: String): T
}
data class Dog(
override val id: String
): Animal<Dog> {
override fun <T : Animal> withSound(sound: String): T {
TODO("Not yet implemented")
}
override fun withSound(sound: String): Dog {
TODO("Not yet implemented")
}
}
Tobias Berger
08/26/2020, 5:28 PMTobias Berger
08/26/2020, 5:30 PM