转换`=>单位`到`()=>单位` [英] Convert `=> Unit` to `() => Unit`

查看:72
本文介绍了转换`=>单位`到`()=>单位`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此块的类型是什么:callback: => Unit?

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

如何将其分配给Option?换句话说,如何更新以下代码,使其没有任何编译错误?

How I can assign it to Option? In other words how to update following code so it doesn't have any 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] 
  }

好.我使用Some(callback _)而不是Some(callback)解决了它.但是为什么要这样做呢?

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

推荐答案

编译器需要知道您是否希望立即执行回调.在没有下划线的情况下,将立即执行,并将结果分配给Some.使用下划线,编译器知道不应执行回调来获取结果,而应将其视为传递给Some构造函数的参数(或更确切地说,apply()方法).

The compiler needs to know whether you want callback to be executed immediately or not. WIthout the underscore immediate execution is assumed, and the result is assigned to the Some. WIth the underscore, the compiler knows that it shouldn't execute callback to get the result but should treat it as the parameter to pass to the Some constructor (or rather, apply() method).

这篇关于转换`=>单位`到`()=>单位`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆