我有以下Scala代码:
maybeEvent.fold(
logAndExecute(s"$key is not a triggered key")(().asRight[Exception])
)(
logAndExecute(s"$key is a triggered key")(storeAndPublishEvent(_))
)
字符串maybeEvent
是Option[Event]
的类型,logAndExecute
看起来像:
def logAndExecute[T](message: String)(executor: => T): T = {
logger.info(message)
executor
}
型
当maybeEvent
是None
时,我得到了两个日志:
key is not a triggered key
key is a triggered key
型
当我把代码改为
maybeEvent.fold(
logAndExecute(s"$key is not a triggered key")(().asRight[Exception])
)(event =>
logAndExecute(s"$key is a triggered key")(storeAndPublishEvent(event))
)
型
问题已解决。你能告诉我这里有什么不同吗?提前感谢!
1条答案
按热度按时间qij5mzcb1#
_
属于内部作用域_
没有错,但在嵌套结构中,我宁愿写x => f(g(x))
storeAndPublishEvent
扩展为storeAndPublishEvent _
storeAndPublishEvent _
扩展为e => storeAndPublishEvent(e)
storeAndPublishEvent(_)
扩展为e => storeAndPublishEvent(e)
val t: Event => Unit = storeAndPublishEvent
并确保Event => Unit
可以被视为另一种类型T
logAndExecute[T](message: String)(executor: => T): T
的签名非常有趣。通过写入logAndExecute("...")(storeAndPublishEvent(_))
,storeAndPublishEvent(_)
成为一个函数(T
=Event => Unit
),logAndExecute
将其返回。而且,实际上不太可能,但在您的情况下,它符合Option.fold
的第二个参数,即Event => Unit
。但是要生成这个函数,需要调用logAndExecute
。