简体   繁体   English

Kotlin Lambda参数与抽象值

[英]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? 最好将lambda函数传递给用作父类的类:将其作为参数传递或在pasrent类中将其定义为抽象lambda,然后在子类中覆盖它?

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: 或定义它以在pasrent类中将其定义为抽象lambda,然后在子类中覆盖它:

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: 看来TheWeapon可以提供lambda本身,并且不将其作为参数,因此您可以将代码从lambda移至抽象函数:

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. 如果TheWeapon通过其构造函数从外部来源接收到lambda,则您必须采用另一种方式,并且让Weapon也将lambda用作构造函数参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM