Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin lambda parameter vs. abstract value

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?

like image 493
S. Entsov Avatar asked Sep 12 '26 14:09

S. Entsov


1 Answers

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.

like image 88
zsmb13 Avatar answered Sep 14 '26 19:09

zsmb13