gpt4 book ai didi

scala - 如何将隐式 Action val 覆盖到 Play 框架 2 中

转载 作者:行者123 更新时间:2023-12-04 05:14:00 24 4
gpt4 key购买 nike

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

/* 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())
}}
感谢您提供任何线索!

最佳答案

Scala 中隐式值的好处在于您可以覆盖它们,方法是在作用域中声明您自己的隐式值(在您的情况下在 if 块中)或通过显式传递它(在您的情况下是模板,例如 views.html.showCity(session = myOtherSession) ) .

关于scala - 如何将隐式 Action val 覆盖到 Play 框架 2 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14536290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com