HelloCW
HelloCW

Reputation: 2335

What does the keyword object mean in Kotlin?

The Code A is from CameraXBasic

I can't understand completely the code private val volumeDownReceiver = object : BroadcastReceiver().

I think the Code B will work well, but in fact it failed.

What does the keyword object mean in Kotlin ?

Code A

private val volumeDownReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        ...
    }
}

Code B

private val volumeDownReceiver = BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        ...
    }
}

Upvotes: 1

Views: 148

Answers (1)

dkarmazi
dkarmazi

Reputation: 3259

In Code A val volumeDownReceiver = object : BroadcastReceiver() refers to creating an object of an anonymous class that inherits from type BroadcastReceiver.

In Code B val volumeDownReceiver = BroadcastReceiver() tries to instantiate a new instance of an abstract class and that's why it's failing.

Edit: link to docs: https://kotlinlang.org/docs/reference/object-declarations.html#object-expressions

Upvotes: 3

Related Questions