Is there a way to use lambda when dealing with abs...
# announcements
s
Is there a way to use lambda when dealing with abstract classes? object works but can't use lambda. DialogInterface.OnClickListener is an interface with SAM, BroadcastReceiver is an abstract class with SAM.
Copy code
private val listener = DialogInterface.OnClickListener { _, _ -> println("interface lambda") }
    private val listener1 = BroadcastReceiver { _, _ -> println("abstract class lambda") } // Error cannot create an instance of abstract class
d
object : BroadcastReceiver() { fun ...(a, b) { println("Abstract Class Lambda")}}
Can't recall the specifics of BroadcastReceiver though.
s
Yeah, i was hoping to avoid implementing the method explicitly and use a lambda instead similar to the interface approach
a
It doesn't work for abstract classes, because an abstract class can have internal state/constructors
d
Of course, that doesn't stop you from creating an extension that will do it for you, if readability is the concern.
s
Did you mean a factory? as BroadcastReceiver is abstract
k
A function that takes a function parameter and returns an instance of the abstract class that just redirects the function to the parameter.
s
I got that, but how can i invoke the extension function on abstract class?
Copy code
fun BroadcastReceiver.newInstance( block : ( Context?, Intent? ) -> Unit ) : BroadcastReceiver {
        return object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                block( context, intent )
            }
        }
    }
k
Don't make it an extension function, I'm guessing that was a mistake.
s
ah
k
So yes, kind of a factory.
👍 1
s
Cool, got it
k
You might even be able to call the function
BroadCastReceiver
so it looks neater at the callsite.
s
Sure
a
Well the extension function would work for the method that would retrieve the abstract class with SAM to take a function which would then convert it to the class