2

我需要在它传递给模板之前覆盖隐式值,但不知道如何。像这样的东西:

/* This Session User and City setup */

case class MySession(user: Option[User] = None, city: Option[City] = None) {}


/* Trait for Controllers */

trait CMySession {
    implicit def mySession[A](implicit request: Request[A]) : MySession = {
        val userOpt = /*... get from session user here ...*/
        val cityOpt = /*... get from session city here ...*/
        MySession(user = userOpt, city = cityOpt)
    }
}


/* Controller */

def showCity(city_name: String) = Action { implicit request =>
    // Get city
    val cityOpt = { for (c <- mySession.city) yield Some(c) } getOrElse Cities.getByName(city_name)
    // Check if NO City in session, but we get it from request
    if (mySession.city != cityOpt) {
       // NEED some how override implicited mySession value here for template?!
    }
    Ok(views.html.showCity())
}}

感谢您提供任何线索!

4

1 回答 1

3

Scala 中隐式值的好处在于,您可以通过在范围内声明自己的隐式值(在您的情况下在 if 块中)或通过显式传递它(在您的情况下为模板,例如views.html.showCity(session = myOtherSession))来覆盖它们。

于 2013-01-26T19:48:23.070 回答