Is it possible to reference a specific inheritor f...
# announcements
s
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
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
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
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
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
I'm sorry, I completely misunderstood. Thanks @Shawn for actually being helpful simple smile
👍 2
😄 1
s
No worries, @karelpeeters! It’s a tough problem to articulate