https://kotlinlang.org logo
#announcements
Title
# announcements
s

Seri

08/14/2019, 6:39 PM
Is it possible to reference a specific inheritor from an abstract parent, rather than any possible inheritor? For example, if I have a
abstract class State
with some helper functions, can I have them return the child type, without it getting generalized to just “anything that inherits from `State`“?
k

karelpeeters

08/14/2019, 6:42 PM
Yes, you just have the inheritor as the return type. Just like everything inherits
Any
and you can still say you return a
String
.
s

Seri

08/14/2019, 6:44 PM
But that’d only work in a case where I’ve got a single inheritor to refer to. What could I do if I wanted to make it reusable?
The best thing I have so far is to describe the parent with the following signature:
abstract class State<S: State<S>>
and each child like so:
sealed class TestState: State<TestState>
but this looks pretty ugly
s

Shawn

08/14/2019, 6:55 PM
ohh
this sounds like you kinda want bootleg self types
via the curiously recurring template pattern
or, rather, that’s what you’re doing
and unfortunately there isn’t a better way of doing it in Kotlin or on the JVM in general 😞
dunno if you already have something like this but, this is how I’d do it:
Copy code
abstract class State<S : State<S>> {
  protected abstract fun self(): S

  fun helperFunc(): S {
    doHelperStuff()
    return self()
  }
}
and have children implement the
self()
method by just returning
this
assuming you want to return the child itself - otherwise just having the return type be
S
and keeping things abstract works fine
s

Seri

08/14/2019, 7:07 PM
Ah, gotcha, thanks @Shawn! I think I’ll just have to keep things abstract and always work with S in the parent class.
👍 1
k

karelpeeters

08/14/2019, 7:15 PM
I'm sorry, I completely misunderstood. Thanks @Shawn for actually being helpful simple smile
👍 2
😄 1
s

Seri

08/14/2019, 7:26 PM
No worries, @karelpeeters! It’s a tough problem to articulate
2 Views