Anonymous class which extends interface, and/or correct way to do this in Kotlin


This probably is in the docs somewhere if I search carefully, but how do I do this in Kotlin (since Runnable is an interface and doesn't have a constructor, I think Kotlin doesn't like this):

  private fun updateResultView(msg : String) : Unit {   runOnUiThread(object : Runnable() {            public override fun run() : Unit {            resultView?.setText((msg))            }   })   }

Also, I know this is very ugly code in Kotlin, can someone remind me what the right way to do this is?  (runOnUiThread is a method in Android Activity superclass).  What I really want to do is create Kotlin extension function that I can reuse in ANY activity class.  

The Java-Kotlin code converter works awesome!  This is the one issue I found with it (and I wanted to get started quickly and just convert some code to Kotlin, and then refactor it slowly as I go.)


As of compilation error: simply remove the parentheses after Runnable.

To do this code more nicely you might want to get rid of the Runnable by introducing a funciton that converts a funciton to a Runnable:

fun r(f: () -> Unit) : Runnable = object : Runnable {   public override fun run() {   f()   } }

And now you'd say

  private fun updateResultView(msg : String) : Unit {   runOnUiThread(r {            resultView?.setText(msg)   })   }

Or, better do runOnUiThread() as an extension function:

  fun Activity.runOnUiThread(f: () -> Unit) {   runOnUiThread(object : Runnable() {            public override fun run() : Unit {            f()            }   })   }

And then it will simply be

funOnUiThread {   resultView?.setText(msg) }

If you encounter a problem with the Java2Kotlin converter, please report it to our tracker. Thanks!


Thanks so much, Andrey.  This Activity.runOnUiThread is exactly what I was looking for :)  but couldn't figure out how to write it, I guess I'm still not very good "thinking in Kotlin", higher order functions, etc.

By the way, is there any thoughts for adding package with these sort of extension functions (I can think of several extension functions already that would be useful).  Would you accept contributions in this area?

I was searching and I see that there is already a kotlin.concurrent package that has some TimerTask and thread functions that would be useful in Android, but there is also other stuff in Android, such as Handlers and of course all the UI stuff.


We have just strated working on the android support: porting SDK examples to Kotlin and fixing many misterious bugs. I think, the time is perfect for such contributions as Android-specific extension functions. Please, feel free to create a kotlin-android directory under the libraries:, and put your extensions there. Thanks.