Convert `=> Unit` to` () => Unit`

What is the type of this block: callback: => Unit ?

How can I assign it to Option ? In other words, how to update the following code so that it does not have compilation errors?

  var onEventCallback: Option[() => Unit] = None def onEvent(callback: => Unit) { onEventCallback = Some(callback) // HERE compilation error: Some[Unit] doesn't conform to Option[() => Unit] } 

Ok I solved this using Some(callback _) instead of Some(callback) . But why is this work?

+1
source share
2 answers

The compiler needs to know if you want the callback to be executed immediately or not. WIthout immediately executes the underscore, and the result is assigned to Some. Underlined, the compiler knows that he should not call back to get the result, but should consider it as a parameter to go to the Some constructor (or rather, apply ()).

+4
source

But why is this work?

Sometimes you can think of a by-name parameter as a function with no arguments. This is actually the phase of Function0 after erasure in the compiler. You can compile the code with -Xprint:erasure to see this:

 def onEvent(callback: Function0): Unit = onEventCallback_=(new Some(callback)) 
+3
source

Source: https://habr.com/ru/post/1494394/


All Articles