i'd like any instance of a class that inherits fro...
# getting-started
h
i'd like any instance of a class that inherits from
Bar
to be able to call
foo()
and return its own type
d
I think you've run into a common problem that shows up in the Java type system. You can generify Bar so it looks like
fun foo(): T = ...
and Baz but that has its own set of problems it introduces.
h
yeah, that introduces A LOT of extra code to fix this small problem
d
To me the biggest issue is that it (the generification pattern aka. the curiously recurring template pattern) tends to play poorly with inheritance, there are some work arounds but it gets increasingly ugly.
h
it's kind of ridiculous that the primordial object oriented programming language (java) has such a fundamental issue with inheritance, huh?
d
That's kind of off-topic, but I agree. I think it stems from C++ "OO" being poor, and while Java is better in a number of ways, it doesn't really have many of the features I would expect from a "real" OO language.
j
Copy code
abstract class Bar<T : Bar<T>> {
    abstract fun subBar(): T
    fun foo(): T = subBar()
}


class Baz : Bar<Baz>() {
    override fun subBar(): Baz {
        return this
    }

}

val a: Baz = Baz()
val b: Baz = a.foo()
compiles at least
d
Yeah, it does what you would expect, the problem is inheriting from
Baz
has complications.
h
i think this is one of the many reasons why everyone in programming is starting to abandon inheritance for just interfaces
d
Kotlin interface delegates actually make that a reasonable approach without introducing a lot of copypasta.
h
yeah, i agree