Writing Android event handlers in Kotlin

Jul 8, 2013 AndroidKotlin

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

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

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()
}

See also First Steps in SAM Conversions.

« Previous Next »