applyOrElse Scala 中缺少参数类型

Missing parameter type in applyOrElse Scala

我在这段代码中尝试调用部分函数。当我构建我的项目时,我收到一条错误消息 missing parameter type ++ headerExtractor.applyOrElse(event, _ => Map.empty)

我看过其他帖子,但我觉得这应该行得通。我做错了什么?

我在这里调用 headerExtractor

private def publishToProfileExchange(customer: Schema.Customer, event: Schema.CustomerEvent): Future[Done] = {
  val messageType: String = "ProfileEvent"
  val headers: Map[String, AnyRef] = Map(
    "profileId" -> customer.id.toString,
    "eventType" -> event.eventType,
    "type" -> messageType
  ) ++ headerExtractor.applyOrElse(event, _ => Map.empty)

  ...
  //valid return values would be here
}

private val headerExtractor: PartialFunction[Schema.CustomerEvent, Map[String, AnyRef]] = {
    case x if x.eventType.equalsIgnoreCase("message") && (x.eventData \ "incoming").asOpt[Boolean].getOrElse(false) =>
       Map("incomingMessage" -> "true")
}

您必须在 .applyOrElse() 上提供 参数类型 。请参阅下面的示例

case class CustomerEvent(eventType: String, eventData: String)

val headerExtractor = new PartialFunction[CustomerEvent, Map[String, AnyRef]] {
  def apply(x: CustomerEvent): Map[String, AnyRef] = Map("incomingMessage" -> "true")
  def isDefinedAt(x: CustomerEvent): Boolean = x.eventType.equalsIgnoreCase("message")
}

assert(headerExtractor.applyOrElse(CustomerEvent("message", "{}"), (customerEvent: CustomerEvent) => Map.empty)
  == Map("incomingMessage" -> "true"))

// or simply do (_: CustomerEvent)

assert(headerExtractor.applyOrElse(CustomerEvent("message", "{}"), (_: CustomerEvent) => Map.empty)
      == Map("incomingMessage" -> "true"))

否定案例

assert(headerExtractor.applyOrElse(CustomerEvent("something-else", "{}"), (_: CustomerEvent) => Map.empty) 
== Map())