3

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?

Eric
  • 16,397
  • 8
  • 68
  • 76
S. Entsov
  • 53
  • 6

1 Answers1

3

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.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • I pass the function to another object, so it's easier to understand the structure if the function is lambda. Also I define the function in 'TheWeapon' class, so it isn't necessary to pass it as a parameter. Isn't it easier to read the code if the the lamda is defined in the body of 'TheWeapon' as a val? – S. Entsov Mar 28 '18 at 17:19
  • At the end of the day, that's gonna be up to you. I think an abstract method and its override looks pretty clean. If you need to pass a reference to this function around later, you can do that with a bound method reference of `this::someFunction` inside the `TheWeapon` class. – zsmb13 Mar 28 '18 at 17:36