Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Runnable vs () -> Unit

Tags:

jvm

kotlin

What is major difference between those two?

For example when creating custom class, which handles what thread should do I am left with 2 options:

class ThreadHandler : Runnable {
    private val thread = Thread(this)

    override fun run() {}
}

AND

class ThreadHandler : () -> Unit {
    private val thread = Thread(this)

    override fun invoke() {}
}

I am asking for:

  1. Advantages and disadvantages of each other (because I believe that Runnable is implemented and "() -> Unit" is extended)
  2. Which is preferred way of using in this scenario
like image 398
Patrik Capay SK Avatar asked Nov 08 '25 01:11

Patrik Capay SK


1 Answers

The differences are mainly about language support, interoperability, history, and usage.

() -> Unit is a Kotlin type, representing a function that takes no parameters and returning nothing useful.  These function types are fundamental to Kotlin, and are used throughout the standard library, so you can pass it to umpteen extension functions.  The language syntax also supports them; for example, you can simply append () to run it.

Runnable is a Java interface, defining a single method that takes no parameters and returns nothing useful.  Java doesn't have first-class functions; instead, it gets some of the benefits using interfaces.  (From Java 8, those were formalised as ‘functional interfaces’ and could be implemented by lambdas where the context provided enough info; but Runnable itself dates right back to Java 1.0.)  There's less language support for them, so you'd have to append .run() to run it.  Also, although they're general-purpose, Runnables are often used to provide code for a thread to execute, so are associated with that execution model.

So while the two constructs mean roughly the same thing, the former looks more natural and interoperates much better with lots of Kotlin code, while the latter interoperates better with older Java code and tends to be used for threads.

And to answer your specific points:

  1. Yes, being a type, I think () -> Unit is technically extended rather than implemented, but the difference isn't significant here.

  2. Unless you have a particular need to interoperate mainly with older Java code, I'd recommend using the Kotlin function type.

like image 152
gidds Avatar answered Nov 10 '25 16:11

gidds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!