[英]Scala empty default closure?
just a quick question I seem to be unable to find an answer to. 只是一个简单的问题,我似乎无法找到答案。
I have a method definition in Scala that looks like this: 我在Scala中有一个方法定义,如下所示:
def execute(goals: List[String],
profiles: List[String] = List(),
loggingCallback: (String) => Unit = { _ => }): Result = {
// method body
loggingCallback("a message")
}
I would like to know whether there is a better way to specify a default empty closure. 我想知道是否有更好的方法来指定默认的空闭包。 The question is not about how to implement logging, this is just an example.
问题不在于如何实现日志记录,这只是一个例子。
Your solution is fine. 你的解决方案很好。 You could introduce a type alias for
Function1[X, Unit]
; 你可以为
Function1[X, Unit]
引入一个类型别名; use ()
as per Kevin's answer, and drop unnecessary parens. 按照Kevin的回答使用
()
,并删除不必要的parens。
scala> type Effect[-A] = (A => Unit)
defined type alias Effect
scala> def foo(f: Effect[String] = _ => ()) = ()
foo: (f: (String) => Unit)Unit
You could also define a noop
function: 您还可以定义一个
noop
函数:
scala> val noop = (a: Any) => ()
noop: (Any) => Unit = <function1>
scala> def foo(f: Effect[String] = noop) = ()
The value ()
is an instance of unit, so this should do the trick: value
()
是unit的一个实例,所以这应该可以解决问题:
def execute(
goals: List[String],
profiles: List[String] = Nil,
loggingCallback: (String) => Unit = { _ => () }): Result =
{
// method body
loggingCallback("a message")
// do something returning a Result
}
update 更新
If something is optional, then it often makes more sense to state so explicitly, this also results in better self-documenting code: 如果某些东西是可选的,那么明确说明通常更有意义,这也会产生更好的自我记录代码:
def execute(
goals: List[String],
profiles: List[String] = Nil,
loggingCallback: Option[(String) => Unit] = None): Result =
{
// method body
loggingCallback forEach { _.apply("a message") }
// do something returning a Result
}
update 2 更新2
DSL-esque situations like this are also one of the very few situations where I'll condone the use of null
in Scala: 像这样的DSL-esque情况也是我在Scala中宽恕使用
null
的极少数情况之一:
def execute(
goals: List[String],
profiles: List[String] = Nil,
loggingCallback: (String) => Unit = null
): Result = {
// method body
val log = Option(loggingCallback) getOrElse {_ => ()}
log("a message")
// do something returning a Result
}
Note the Option(loggingCallback)
to immediately convert the nullable loggingCallback
into a nice type-safe Option
, then getOrElse
to provide a fallback alternative. 注意
Option(loggingCallback)
立即将可空的loggingCallback
转换为一个很好的类型安全的Option
,然后getOrElse
来提供一个后备替代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.