是否可以通过传递地图中指定的类来调用一般性函数



在这里问,因为我要拔出头发,试图弄清楚我到底需要做什么。

我正在编写一个批处理端点,该端点试图在执行端点本身内执行逻辑之前将请求的正文转换为特定的Scala案例类。

这是我目前所拥有的。首先,我有一个函数executeWithType,该函数采用通用类型,控制器方法和请求主体,并在将请求主体转换为提供的类型后执行控制器方法。请求参数可在此功能之外的范围内提供。

def executeWithType[A](action: () => Action[A], batchRequest: BatchRequest): Future[Result] = {
    action()(request.map(_ => batchRequest.body.map(_.as[A]).get))
}

然后,我有一些代码,可以检查要调用的端点以及根据batchrequest本身的内容而施放的类型。

val res: Future[Result] = (batchRequest.method, batchRequest.endpoint) match {
    case ("POST", "/endpoint1") => {
        executeWithType[EndpointOneType](controller.endpointOne _, batchRequest)
    }
    case ("POST", "/endpoint2") => {
        executeWithType[EndpointTwoType](controller.endpointTwo _, batchRequest)
    }
    case _ => Future.successful(NotFound)
}

上面的工作非常好 - 但是,如果可能的话,我想避免使用单独情况的元组匹配,并指定执行此操作的地图。在我理想的世界中,上面的代码块的最终结果看起来像这样:

val actions = Map(
    Seq("POST", "/endpoint1") -> (controller.endpointOne _, EndpointOneType),
    Seq("POST", "/endpoint2") -> (controller.endpointTwo _, EndpointTwoType)
)
val res = actions.get(Seq(batchRequest.method, batchRequest.endpoint)) match {
    case Some(action) => {
         executeWithType[action._2](action._1, batchRequest)
    }
    case _ => Future.successful(NotFound)
}

这根本可以吗?我一直在尝试与之抗争,但是我对Scala中反思的理解确实很弱,因此我不确定我确切地做到这一点。我已经尝试了一堆classof和typetag和类[_]的东西,但我基本上是在黑暗中摇摆。希望有人比我知识渊博的人能帮助我。

大事是:

  1. 在地图的值中,在元组的第二个空间中需要做什么?您如何通过类变量?
  2. 我们如何使用该类别可变性来调用一般键入的方法?

我们如何使用该类别可变性来调用一般键入的方法?

你不能。但是我想建议一个替代解决方案。

只是定义本地类而不是元组:

class RequestAction[A](action: () => Action[A]) {
  def apply(request: BatchRequest) = executeWithType(action, request)
}
val actions = Map(
    Seq("POST", "/endpoint1") -> new RequestAction(controller.endpointOne _), // type parameter is inferred
    Seq("POST", "/endpoint2") -> new RequestAction(controller.endpointTwo _)
)
val res = actions.get(Seq(batchRequest.method, batchRequest.endpoint)) match {
    case Some(action) => action(batchRequest)
    case _ => Future.successful(NotFound)
}

(虽然这取决于问题中未显示的代码,但似乎可以通过传递Action[A]而不是() => Action[A]来简化)。

最新更新