PedroD
PedroD

Reputation: 6023

Is there even a simpler way to express anonymous classes in Kotlin?

I translated this Java

new Thread("Cute Thread") {
  public void run() {
    int a = 3;
  }
}.start();

to this Kotlin

object : Thread("Cute Thread") {
  override fun run() {
     val a = 3
  }
}.start()

But I feel that there is a simpler way of doing this, however I can't find any examples.

I've tried

  Thread("Cute Thread") { val a = 3 }.start()

But with no success...

PS. I know that starting a Thread like this is a bad practice.

Upvotes: 3

Views: 2285

Answers (4)

Jayson Minard
Jayson Minard

Reputation: 85946

One issue here is that the Thread class constructor has parameters in a bad order for Kotlin. For Runnable you can easily use a SAM conversion (a single method interface can be treated as a lambda) but because the lambda is not the last parameter it looks kinda clunky. In the case where there is only one parameter it is fine:

Thread { val a = 3 }.start()

However with more than one parameter, they are backwards causing this uglier syntax with the lambda as a parameter inside the parenthesis:

Thread({ val a = 3 }, "some name").start()

Instead you should use the Kotlin stdlib function thread()

With that function you have simpler syntax of:

// create thread, auto start it, runs lambda in thread
thread { val a = 3 }  

// create thread with given name, auto start it, runs lambda in thread
thread(name = "Cute Thread") { val a = 3 }  

// creates thread that is paused, with a lambda to run later
thread(false) { val a = 3 } 

// creates thread that is paused with a given name, with a lambda to run later
thread(false, name = "Cute Thread") { val a = 3 } 

See also: thread() function documentation

Upvotes: 3

klimat
klimat

Reputation: 24991

There's no different way to implement an anonymous class (except SAM conversions).
But you can still simplify your code by:

 Thread({ val a = 3 }).start()

or with thread name:

Thread({ val a = 3 }, "Cute Thread").start()

Upvotes: 6

voddan
voddan

Reputation: 33769

You code is absolutely correct. The only way to simplify it is it extract the logic into a function and then reuse it:

fun newThread(name: String, block: () -> Unit): Thread {
    return object : Thread(name) {
        override fun run() = block()
    }.start()
}

Usage:

newThread("Cute Thread") {
    val a = 3
}

Upvotes: 2

Koziołek
Koziołek

Reputation: 2874

If you want to extend/implement some class/interface in your anonymous class there is no other way than:

object: Thread("Name"){
    //...
}.start()

The simplest possible construction is of course:

val adhoc = object{
    // some code here
}

but there are no simpler way to do this.

Documentation, but You probably read that.

Upvotes: 1

Related Questions