Scala 空默认闭包?
只是一个简单的问题,我似乎无法找到答案。
我在 Scala 中有一个方法定义,如下所示:
def execute(goals: List[String],
profiles: List[String] = List(),
loggingCallback: (String) => Unit = { _ => }): Result = {
// method body
loggingCallback("a message")
}
我想知道是否有更好的方法来指定默认的空闭包。问题不在于如何实现日志记录,这只是一个示例。
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:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的解决方案很好。您可以为
Function1[X, Unit]
引入类型别名;按照凯文的回答使用()
,并删除不必要的括号。您还可以定义一个
noop
函数:Your solution is fine. You could introduce a type alias for
Function1[X, Unit]
; use()
as per Kevin's answer, and drop unnecessary parens.You could also define a
noop
function:值
()
是unit的一个实例,所以这应该可以解决问题:update
如果某些东西是可选的,那么明确地声明通常更有意义,这也产生更好的自文档化代码:
update 2
像这样的 DSL 式情况也是我会容忍在 Scala 中使用
null
的极少数情况之一:请注意
Option(loggingCallback)
立即将可空loggingCallback
转换为一个很好的类型安全Option
,然后< code>getOrElse 提供后备替代方案。The value
()
is an instance of unit, so this should do the trick:update
If something is optional, then it often makes more sense to state so explicitly, this also results in better self-documenting code:
update 2
DSL-esque situations like this are also one of the very few situations where I'll condone the use of
null
in Scala:Note the
Option(loggingCallback)
to immediately convert the nullableloggingCallback
into a nice type-safeOption
, thengetOrElse
to provide a fallback alternative.