https://kotlinlang.org logo
Title
h

Hullaballoonatic

05/15/2019, 6:19 PM
i'd like any instance of a class that inherits from
Bar
to be able to call
foo()
and return its own type
d

dalexander

05/15/2019, 6:20 PM
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

Hullaballoonatic

05/15/2019, 6:21 PM
yeah, that introduces A LOT of extra code to fix this small problem
d

dalexander

05/15/2019, 6:23 PM
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

Hullaballoonatic

05/15/2019, 6:23 PM
it's kind of ridiculous that the primordial object oriented programming language (java) has such a fundamental issue with inheritance, huh?
d

dalexander

05/15/2019, 6:25 PM
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

Joe

05/15/2019, 6:28 PM
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

dalexander

05/15/2019, 6:30 PM
Yeah, it does what you would expect, the problem is inheriting from
Baz
has complications.
h

Hullaballoonatic

05/15/2019, 6:32 PM
i think this is one of the many reasons why everyone in programming is starting to abandon inheritance for just interfaces
d

dalexander

05/15/2019, 6:34 PM
Kotlin interface delegates actually make that a reasonable approach without introducing a lot of copypasta.
h

Hullaballoonatic

05/15/2019, 6:34 PM
yeah, i agree