Writing Android event handlers in Kotlin

Updated: 2013-08-20: For Kotlin M6 compatibility.
Published: 2013-06-08

Kotlin is Jetbrains successor to Java, this brief post illustrates how Kotlin’s SAM conversions can simplify Android event handlers.

Kotlin can synthesize anonymous SAM class instances, this removes all the redundant verbosity of Java-style handlers. All you need to provide is the event handler in the form of a function literal. For example, this Android onClick handler written in Java:

button1.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // Handler code here.
        Toast.makeText(this.MainActivity, "Button 1",
                Toast.LENGTH_LONG).show();
    }
});

Translates literally to this Kotlin code:

button1.setOnClickListener(object: View.OnClickListener {
    override fun onClick(view: View): Unit {
        // Handler code here.
        Toast.makeText(this@MainActivity, "Button 1",
                Toast.LENGTH_LONG).show()
    }
})

Which is equivalent (courtesy of an implicit SAM conversion) to this beautifully simple idiomatic Kotlin code:

button1.setOnClickListener {
    // Handler code here.
    Toast.makeText(this, "Button 1",
            Toast.LENGTH_LONG).show()
}
  • It’s not necessary to declare the single view function parameter, use the implicitly declared it parameter.
  • Argument parentheses can be omitted from View.setOnClickListener because it is passed a single function literal argument.
  • In the Java-style examples this inside the handler refers to the anonymous class instance; in the final idiomatic Kotlin example this refers to the instance lexically enclosing the handler not the anonymous class object (which makes a lot more sense).

See also First Steps in SAM Conversions.

About these ads

%d bloggers like this: