How to bridge Java Runnable with Kotlin Closures


#1

Hello,

I would like to do something like this:

val list = ArrayList<Runnable>()
val func = { println(“hi”) }
println(func.javaClass.getName())
list.add(func)


Obviously, this won’t compile. Reason I want to do something like that is that I want to use HawtDispatch from within Kotlin code and I have to take HawtDispatch the way it was made. When I print the class name of func I get something like namespace$main$func$1. So that doesn’t give me a hint.

This code here in Groovy works and prints “hi” to the console:

def list = new ArrayList<Runnable>()
def clos = { println(“hi”) }
list.add(clos)
list.get(0).run()


Is there some way to achieve the same in Kotlin? Then I find no way to get something like this to compile:

  var runnable = Runnable()
  {
  public fun run() {
           println(“foo”)
  }
  }


Any hints appreciated :-).
Cheers, Oliver


#2

You can define a funciton to convert from Kotlin Function0 to Runnable:

``

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

And then say
``

val list = ArrayList<Runnable>()
val func = r { println(“hi”) }
println(func.javaClass.getName()) // this will be Runnable
list.add(func)


#3

We also have a function "runnable" in kotlinLib - a helper function for creating a Runnable from a function

``

  val list = ArrayList<Runnable>()
  val clos = runnable {
           println(“hi”)
           }
  list.add(clos)
  list.get(0).run()


#4

Kool! That was helpful and very quick ;-). Thanks.


#5

Simpler solution would be
fun r(f: () -> Unit): Runnable = Runnable { f() }