Scala single method interface implementation

前端 未结 3 663
夕颜
夕颜 2020-12-03 20:45

Does Scala have any syntactic sugar to replace the following code:

val thread = new Thread(new Runnable {
   def run() {
     println(\"hello world\")
   }           


        
3条回答
  •  萌比男神i
    2020-12-03 21:37

    SAM types are supported using invokeDynamic since scala-2.12 similar to JDK-8, Below was tested on 2.12.3 - Release notes about SAM can be found here - http://www.scala-lang.org/news/2.12.0/

    object ThreadApp extends App {
      println("Main thread - begins")
      val runnable: Runnable = () => println("hello world - from first thread")
    
      val thread = new Thread(runnable)
      println("Main thread - spins first thread")
      thread.start()
    
      val thread2 = new Thread(() => println("hello world - from second thread"))
      println("Main thread - spins second thread")
      thread2.start
      thread.join()
      thread2.join()
    
      println("Main thread - end")
    }
    

提交回复
热议问题