scala control

The following function executes a piece of code in a thread:


def runThread(block:()=>Unit){

      new Thread{

orverride def run(){block()}

}.start()

}

This code is given as a function of type () => Unit. However, when you call the function, you need to write that unbeautiful ()=>:

runInThread(()=>println("Hi");Thread.sleep(1222);println("bye"))


To omit ()=> in a call, use the call-by-name notation: omit () in parameter declarations and call the function arguments, but keep =>:

def runInThread(block:=>Unit){

  new Thread{

orverride def run(){block()}

}.start()

}

In this way, the calling code becomes runInThread{println("")

;Thread.sleep(1222);println("bye")

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324908609&siteId=291194637