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.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With