1

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) {
        ...
    }
}
HelloCW
  • 843
  • 22
  • 125
  • 310
  • `object` keyword can also be used to create [anonymous class](https://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java). Using that, you are saying that you want to override one or more member of either concrete or abstract member. This way, you don't need to create a separate class to and trim down the functionality to your needs. I would suggest reading about [object](https://kotlinlang.org/docs/reference/object-declarations.html). – Taseer Sep 10 '19 at 00:33

1 Answers1

3

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

dkarmazi
  • 3,199
  • 1
  • 13
  • 25