Delegate with a reference to the delegating class?

It’s likely the title isn’t helpful, so here’s a rough sketch of the problem: I’m bringing a game project from Dart/Flutter over to Kotlin (plus libgdx).

In it, I have a few different kinds of game object that share a set of properties. Through some moderately expensive calculations, those properties get transmuted into gameplay-relevant statistics. For a concrete example, both canonical aircraft designs, and individual instances of that aircraft, have size, engine power, and year of production properties. Some math happens, and speed, agility, and toughness come out the other end.

In Dart, I managed this with a mixin: mixin AircraftStatsCalculator on AircraftProperties, and Aircraft extends AircraftProperties with AircraftStatsCalculator. A few types implemented AircraftProperties, and AircraftStatsCalculator was both interface and delegate.

It doesn’t look like I can do exactly that in Kotlin. This is the best I’ve come up with so far:

“` class AircraftDesign ( // … input, implementing AircraftProperties ) : AircraftProperties, AircraftStats { private val statsCache: AircraftStatsCalculator = AircraftStatsCalculator(this)

override val speed: Die get() = statsCache.speed 

“`

It would be nice not to have to implement each member of AircraftStats in AircraftDesign, and delegate fully to AircraftStatsCalculator. Is there some way to feed AircraftStatsCalculator a this reference earlier, or some alternate Kotlin design pattern applicable to this situation I haven’t come across yet?

submitted by /u/-fishbreath
[link] [comments]