ThomasFromUganda
ThomasFromUganda

Reputation: 410

Cannot override handleMessage when creating new Handler with Kotlin?

I am following the answer I found here.

This is how I expect to be able to create a new Handler and override the handleMessage() function without having to declare it as a new class:

val handler = Handler {
    override fun handleMessage(msg: Message?) {

    }
}

However, this doesn't work and gives me two errors:

  1. Modifier 'override' is not applicable to local function
  2. Expected a value of type Boolean

How exactly can I just create a new Handler and override the handleMessage() function without having to declare a new class?

Upvotes: 0

Views: 877

Answers (1)

Jaymin
Jaymin

Reputation: 2912

Make the instance using object Expressions. This will let you override all the class methods.

Read more about this Here

Replace your code with this.

 val handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
        }
    }

Upvotes: 2

Related Questions