What's the difference between => , ()=>, and Unit=>

后端 未结 4 1786
深忆病人
深忆病人 2020-11-22 16:40

I\'m trying to represent a function that takes no arguments and returns no value (I\'m simulating the setTimeout function in JavaScript, if you must know.)

c         


        
4条回答
  •  余生分开走
    2020-11-22 17:29

    In the question, you want to simulate SetTimeOut function in JavaScript. Based on previous answers, I write following code:

    class Scheduled(time: Int, cb: => Unit) {
      private def runCb = cb
    }
    
    object Scheduled {
      def apply(time: Int, cb: => Unit) = {
        val instance = new Scheduled(time, cb)
        Thread.sleep(time*1000)
        instance.runCb
      }
    }
    

    In REPL, we can get something like this:

    scala> Scheduled(10, println("a")); Scheduled(1, println("b"))
    a
    b
    

    Our simulation doesn't behave exactly the same as SetTimeOut, because our simulation is blocking function, but SetTimeOut is non-blocking.

提交回复
热议问题