在 Scala 模式匹配中从昂贵的语句中别名对象 [英] Aliasing objects from expensive statements in Scala pattern match

查看:31
本文介绍了在 Scala 模式匹配中从昂贵的语句中别名对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个昂贵的 case 语句,需要访问数据库以确定完全匹配.如果匹配,则必须使用上述调用的结果来执行进一步的操作:

I have an expensive case statement which needs to hit the database to determine a complete match. If there is a match, the result from the aforementioned call must be used to perform further operations:

def intent = {
    case request @ GET(Path(Seg(database :: Nil))) if recordsFrom(database) != Nil =>
        renderOutput(recordsFrom(database))
    case ...
}

我只想调用 recordsFrom(database) 一次.在上面的例子中,它被调用了两次.似乎我应该能够对语句应用一些别名?

I would like to call recordsFrom(database) only once. In the above example, it is called twice. It seems like I should be able to apply some alias to the statement?

推荐答案

Lawrence,据我所知,您正在使用 Unfiltered 来处理 RESTful 请求,但您还将数据库查找与该响应过滤相结合.我建议你不要那样做.相反,我会安排如下:

Lawrence, from what I'm seeing you're using Unfiltered to handle a RESTful request but you've also combined a database lookup with that response filtering. I would advise you not to do that. Instead I'd arrange things as following:

val dbReqCommand = new DBRequestCommand(myDbConPool)

def intent ={
  case req @ GET(Path(Seq(database :: Nil))) => dbReqCommand(req, database)
}

其中您将数据库请求封装在一个对象中,您可以将其替换为测试目的(想想没有数据库后端的集成测试.)在请求处理程序中,您可能会放入响应:

Wherein you've encapsulated the db requests in an object that you could substitute out for testing purposes (think integration tests without a DB backend.) Within the request handler you might then put in the response:

Option(recordsFrom(database)) match{
  case Some(value) => OK ~> renderOpupt(value)
  case None => //an error response or Pass
}

那样你可能会得到一些类似的东西:

That way you might have something along the lines of:

trait DBReqPlan{
  def dbReqCommand: RequestCommand[String]

  def intent ={
   case req @ GET(Path(Seq(database :: Nil))) => dbReqCommand(req, database)
  }
}

哪个更容易测试和使用.

which is easier to test against and work with.

这篇关于在 Scala 模式匹配中从昂贵的语句中别名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆