0

I'm a newbie to Kotlin. I'm trying to convert my old java code into Kotlin. When I try to create a new Handler and override handleMessage() method I got an answer at: How to use Handler and handleMessage in Kotlin?

private val mHandler = object : Handler() {

override fun handleMessage(msg: Message?) {
    // Your logic code here.
}

}

I don't understand what "object : " stands for and why do we need this here ? When I try val mHandler = Hander() {} this got an error and I cannot override handleMessage()

Sơn Tùng
  • 11
  • 6

1 Answers1

3

That's just Kotlin's way of subclassing/implementing an anonymous class and creating a new instead of it in-place.

Java:

//Define an interface (or a class):
public interface Runnable {
    void run();
}

//Create an anonymous class and instantiate it:
Runnable runnable = new Runnable() {
    @Override
    void run() {
        //Do something here
    }
}

Kotlin:

//Define an interface (or a class):
interface Runnable {
    fun run()
}

//Create an anonymous class and instantiate it:
val runnable = object: Runnable() {
    override fun run() {
        //Do something here
    }
}

If you don't write the object: part, then it means that you are instantiating the interface/superclass itself. Which is impossible for interfaces and abstract classes. Also, it's a syntax error to have {} after () without object:.

Mousa
  • 2,190
  • 3
  • 21
  • 34