首页 > 解决方案 > PartialFunction 隐式参数

问题描述

我有一个简单的 PartialFunction

type ChildMatch = PartialFunction[Option[ActorRef], Unit]

def idMatch(msg: AnyRef, fail: AnyRef)(implicit ctx: ActorContext): ChildMatch = {
    case Some(ref) => ref forward msg
    case _ => ctx.sender() ! fail
}

但是当我尝试使用它时 - 编译器想要这样的声明:

...
implicit val ctx: ActorContext
val id: String = msg.id

idMatch(msg, fail)(ctx)(ctx.child(id))

如您所见,它不隐含地将 ctx 作为第二个参数

我如何更改我的 idMatch 函数以像这样使用它:

...
implicit val ctx: ActorContext
val id: String = msg.id

idMatch(msg, fail)(ctx.child(id))

?

标签: scalaakkaimplicitpartial-functions

解决方案


编译器将始终假定第二个参数列表代表隐式参数列表。您必须以某种方式拆分这两个函数的调用。以下是一些可能性:

idMatch(msg, fail).apply(ctx.child(id))

val matcher = idMatch(msg, fail)
matcher(ctx.child(id))

// Provides the implicit explicitly from the implicit scope
idMatch(msg, fail)(implicitly)(ctx.child(id))

推荐阅读