[英]How to ensure implicit variable is passed from trait to method?
我的特質寫成如下:
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,它會起作用,但是我每次都必須在控制器內重復該聲明,並且如果我可以將其隱藏在特征中,代碼看起來會更簡潔。 有什么方法可以將特征中的隱含值傳遞給控制器?
將所述val設為字段變量:
trait NewTrait {
implicit val newTrait = new model.helper.newTrait
...
}
現在它將在方法foo
范圍內。
盡管我發現名稱有些混亂(可能是示例代碼),但是這是可以的:
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
}
}
你可以有:
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.