【问题标题】:How to ensure implicit variable is passed from trait to method?如何确保隐式变量从特征传递到方法?
【发布时间】:2013-02-13 16:05:23
【问题描述】:

我有一个特质写如下:

trait NewTrait { 
  def NewTrait(f: Request[AnyContent] => Result):  Action[AnyContent] = {
    Action { request =>
      implicit val newTrait = new model.helper.newTrait
      f(request) 
    }
  }
}

还有一个使用该特征的控制器,并尝试将隐式 val newTrait 传递给视图:

object Test extends Controller with NewTrait {

  def foo(num: Int) = NewTrait { request =>
    val view = (views.html.example.partials.viewWrap)       
    Ok(views.html.example.examplePage(views.html.shelfPages.partials.sidebar())
}

在 foo 中,newTrait 不在范围内,但是将其纳入范围的最佳做法是什么?对于收到的每个请求,它必须是唯一的。如果我从 foo 中重新声明隐式 val,它会起作用,但我必须每次在控制器中重复该声明,如果我可以将其隐藏在 trait 中,代码看起来会更清晰。有什么方法可以将特征中的隐含值传递给控制器​​?

【问题讨论】:

    标签: scala playframework playframework-2.0


    【解决方案1】:

    将上述 val 设为字段变量:

    trait NewTrait { 
      implicit val newTrait = new model.helper.newTrait
      ...
    }
    

    现在它将在方法 foo 范围内。

    【讨论】:

    • 它将它带入方法的范围,但对于发送的请求将不再是唯一的。例如,在视图的页面刷新时,数据会从该变量中保留下来,但这不是我们所希望的 - 它应该重置。
    • 那么你应该使用包装器。
    【解决方案2】:

    虽然我发现名称有点混乱(可能是示例代码),但您可以这样做:

    trait NewTrait {
      def NewTrait(f: Request[AnyContent] => model.helper.newTrait => Result): Action[AnyContent] = {
        Action { request =>
          val newTrait = new model.helper.newTrait
          f(request)(newTrait)
        }
      }
    }
    

    在使用它的代码中:

    object Test extends Controller with NewTrait {
      def foo(num: Int) = NewTrait { request => implicit newTrait =>
        Ok
      }
    }
    

    【讨论】:

      【解决方案3】:

      你可以拥有:

      trait NewTrait {
          def gotRequest(req:Request) = {
              implicit val newTrait = new model.helper.newTrait
              // don't have to pass the newTrait parameter here 
              // explicitly, it is used implicitly
              Whatever.f(request)
          }
      }
      

      和:

      object Whatever {
          def f(req:Request)(implicit val newTrait:NewTrait) = {
              //newTrait is in scope here.
      
              //...the rest of your code
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-21
        • 2016-08-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多