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

后端 未结 4 1746
深忆病人
深忆病人 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:20

    case class Scheduled(time : Int, callback :  => Unit)
    

    The case modifier makes implicit val out of each argument to the constructor. Hence (as someone noted) if you remove case you can use a call-by-name parameter. The compiler could probably allow it anyway, but it might surprise people if it created val callback instead of morphing into lazy val callback.

    When you change to callback: () => Unit now your case just takes a function rather than a call-by-name parameter. Obviously the function can be stored in val callback so there's no problem.

    The easiest way to get what you want (Scheduled(40, println("x") ) where a call-by-name parameter is used to pass a lambda) is probably to skip the case and explicitly create the apply that you couldn't get in the first place:

    class Scheduled(val time: Int, val callback: () => Unit) {
        def doit = callback()
    }
    
    object Scheduled {
        def apply(time: Int, callback: => Unit) =
            new Scheduled(time, { () => callback })
    }
    

    In use:

    scala> Scheduled(1234, println("x"))
    res0: Scheduled = Scheduled@5eb10190
    
    scala> Scheduled(1234, println("x")).doit
    x
    

提交回复
热议问题