I have an abstract class with two concrete subclas...
# announcements
a
I have an abstract class with two concrete subclasses containing implementations of
fun myFunction()
. The body of both implementations is different, but the last line is the same, calling a function in the abstract superclass. The common last line must be executed last. What is the most appropriate way to use Kotlin language features to refactor out the duplication?
j
Create an abstract
fun
in the abstract class which is called by
myFunction
and override that in the child classes?
👍 1
a
got it - I see what you mean
many thanks!
f
Exactly, same as in Java.
Copy code
abstract class AC {
    fun myFunction() {
        doMyFunction()
        // post logic
    }

    protected abstract fun doMyFunction()
}
j
or maybe I didn't understand the question... you have this?
Copy code
abstract class Parent {
  abstract fun myFunction()
  fun anotherFunction()
}

class FirstChild: Parent {
  fun myFunction() {
    ...
    anotherFunction()
  }
}

class SecondChild: Parent {
  fun myFunction() {
    ...
    anotherFunction()
  }
}
👍 1
a
@José González Gómez exactly that
thanks - although I once did the SCJP certification, I’m coming to Kotlin after a 13 year detour in Objective-C & Swift 😄
j
ok, then would this work?
Copy code
abstract class Parent {
  fun myFunction() {
    this.configurableBehavior()
    this.sharedBehavior()
  }
  fun sharedBehavior() {
    ...
  }
  abstract fun configurableBehavior()
}

class FirstChild: Parent {
  fun configurableBehavior() {
    ...
  }
}

class SecondChild: Parent {
  fun configurableBehavior() {
    ...
  }
}
a
@José González Gómez yes - I think this is identical to what @Fleshgrinder suggested above?
j
yes 🙂
a
great - many thanks to both of you for your help. I see now, I kind of had this inside out. An external reality check is so often super helpful! 👍
👍 2
🙂 2
f
With
Exactly
in my comment I meant that @José González Gómez’s comment is exactly correct (I think it was confusing with the sentence that followed 😄 ).
👍 1