How is better to pass a lambda function to a class that is used as parent: to pass it as a parameter or to define it in the pasrent class as an abstract lambda and then override it in a child class?
To pass it as a parameter:
open class Weapon(val someFunction: () -> Unit) {
...
}
class TheWeapon() : Weapon({ ... }) {
...
}
Or to define it to define it in the pasrent class as an abstract lambda and then override it in a child class:
abstract class Weapon() {
abstract val someFunction: () -> Unit;
...
}
class TheWeapon() : Weapon() {
override val someFunction: () -> Unit = { ... }
...
}
So what solution is better to use?
If you were going to use the second approach, why not just have a method with this type that you override? It seems that TheWeapon can supply the lambda itself and doesn't take it as a parameter, so you could just move the code from the lambda to an abstract function:
abstract class Weapon {
abstract fun someFunction()
}
class TheWeapon : Weapon() {
override fun someFunction() { ... }
}
If TheWeapon receives the lambda from an external source through its constructor, then you have to go the other way, and have Weapon take the lambda as a constructor parameter as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With