当计算currying函数中的Scala代码时,为什么?

b1uwtaje  于 2023-08-05  发布在  Scala
关注(0)|答案(1)|浏览(96)

我有以下Scala代码:

maybeEvent.fold(
          logAndExecute(s"$key is not a triggered key")(().asRight[Exception])
        )(
          logAndExecute(s"$key is a triggered key")(storeAndPublishEvent(_))
        )

字符串
maybeEventOption[Event]的类型,logAndExecute看起来像:

def logAndExecute[T](message: String)(executor: => T): T = {
    logger.info(message)
    executor
  }


maybeEventNone时,我得到了两个日志:

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))
        )


问题已解决。你能告诉我这里有什么不同吗?提前感谢!

qij5mzcb

qij5mzcb1#

  • 没有优先级,没有求值
  • 一切都是为了扩张
  • _属于内部作用域
  • _没有错,但在嵌套结构中,我宁愿写x => f(g(x))
  • storeAndPublishEvent扩展为storeAndPublishEvent _
  • storeAndPublishEvent _扩展为e => storeAndPublishEvent(e)
  • storeAndPublishEvent(_)扩展为e => storeAndPublishEvent(e)
  • 你可以写val t: Event => Unit = storeAndPublishEvent并确保
  • 在scala中,Event => Unit可以被视为另一种类型T
  • logAndExecute[T](message: String)(executor: => T): T的签名非常有趣。通过写入logAndExecute("...")(storeAndPublishEvent(_))storeAndPublishEvent(_)成为一个函数(T = Event => Unit),logAndExecute将其返回。而且,实际上不太可能,但在您的情况下,它符合Option.fold的第二个参数,即Event => Unit。但是要生成这个函数,需要调用logAndExecute

相关问题