Nan Xiao
Nan Xiao

Reputation: 17467

How to understand "new {}" syntax in Scala?

I am learning Scala multi-thread programming, and write a simple program through referring a tutorial:

object ThreadSleep extends App {
  def thread(body: =>Unit): Thread = {
    val t = new Thread {
      override def run() = body
    }
    t.start()
    t
  }
  val t = thread{println("New Therad")}
  t.join
}

I can't understand why use {} in new Thread {} statement. I think it should be new Thread or new Thread(). How can I understand this syntax?

This question is not completely duplicated to this one, because the point of my question is about the syntax of "new {}".

Upvotes: 1

Views: 107

Answers (2)

Chirlo
Chirlo

Reputation: 6132

By writing new Thread{} your creating an anonymous subclass of Thread where you're overriding the run method. Normally, you'd prefer to create a subclass of Runnable and create a thread with it instead of subclassing Thread

val r = new Runnable{ override def run { body } }
new Thread(r).start

This is usually sematincally more correct, since you'd want to subclass Thread only if you were specializing the Thread class more, for example with an AbortableThread. If you just want to run a task on a thread, the Runnable approach is more adequate.

Upvotes: 2

Nicolas Cailloux
Nicolas Cailloux

Reputation: 448

This is a shortcut for

new Thread() { ... } 

This is called anonymous class and it works just like in JAVA: You are here creating a new thread, with an overriden run method. This is useful because you don't have to create a special class if you only use it once. Needs confirmation but you can override, add, redefine every method or attribute you want.

See here for more details: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

Upvotes: 3

Related Questions