简体   繁体   English

将lambda直接分配给继承的抽象方法[Kotlin]

[英]Assign lambda directly to inherited abstract method [Kotlin]

I am subclassing a BroadcastReceiver and would like to be able to specify a lambda as an input parameter and assign it directly to be used as the implementation for "onReceive". 我将一个BroadcastReceiver子类化,并希望能够指定一个lambda作为输入参数,并将其直接分配为用作“ onReceive”的实现。 This is how my code looks like: 这是我的代码的样子:

class Receiver(val callback: (Context?, Intent?) -> Unit): BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent?) = callback

    fun itWorks(context: Context?, intent: Intent?) = callback
}

I would like to be able to instantiate it like: 我希望能够实例化它:

val myReceiver = Receiver({context: Context?, intent: Intent?-> {
    println("Intent received: $intent")
}})

Or 要么

val myReceiver2 = Receiver(::implementationHere)

However I get the following error: 但是我收到以下错误:

Error:(2, 18) Return type of 'onReceive' is not a subtype of the return type of the overridden member 'public abstract fun onReceive(p0: android.content.Context!, p1: android.content.Intent!): kotlin.Unit defined in android.content.BroadcastReceiver' 错误:(2,18)'onReceive'的返回类型不是重写成员'public abstract fun onReceive(p0:android.content.Context !, p1:android.content.Intent!)的返回类型的子类型: android.content.BroadcastReceiver中定义的kotlin.Unit'

Interestingly, I am not getting an error when assigning this lambda to the "itWorks" method. 有趣的是,将这个lambda分配给“ itWorks”方法时,我没有收到错误。 Could you please tell me what's the difference between these two methods? 您能告诉我这两种方法有什么区别吗? Why does it work with one but not the other? 为什么它只能与另一只一起使用? As far as I can tell the signatures are the same in both methods. 据我所知,两种方法中的签名是相同的。

(I'm coming from a Java8 background, where (as far as lambdas go) all you care about is to have the same method signature) (我来自Java8背景,您所关心的(就Lambda而言)具有相同的方法签名)

Of course this works, but I would prefer the other way: 当然可以,但是我更喜欢另一种方式:

class Receiver2(val callback: (Context?, Intent?) -> Unit): BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent?) {
        callback(context, intent)
    }
}

You need to invoke your lambda callback with parameters: 您需要使用以下参数调用lambda callback

    override fun onReceive(context: Context?, intent: Intent?) = callback(context, intent) // returns Unit

This works only because the method's return type becomes (Context?, Intent?) -> Unit (with the method parameters being unused): 这仅起作用是因为方法的返回类型变为(Context?, Intent?) -> Unit (方法参数未使用):

    fun itWorks(context: Context?, intent: Intent?) = callback // returns (Context?, Intent?) → Unit

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

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