2013-02-13 17 views
0

我寫的特點如下:如何確保將隱式變量從特徵傳遞給方法?

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()) 
} 

在富,newTrait贏得」不在範圍內,但將其納入範圍的最佳做法是什麼?每次收到的請求都必須是唯一的。如果我在foo中重新聲明瞭隱式val,那麼它就會起作用,但是我必須在控制器中每次重複聲明,並且如果我可以將特性隱藏起來,那麼代碼將看起來更清晰。有什麼方法可以將特質中的隱含價值傳遞給控制器​​?

回答

0

使上述VAL一個字段變量:

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

現在,這將是法foo範圍。

+0

它將它引入方法的範圍,但它不再是唯一的發送請求。例如,在視圖的頁面刷新時,數據會從該變量中持久存在,但這不是期望的 - 應該重置。 – DaveWeber 2013-02-13 19:09:07

+0

然後你應該使用包裝。 – pedrofurla 2013-02-13 19:46:15

0

雖然我找到的名稱是否是一個有點混亂(它可能示例代碼),這是你如何能做到這一點:

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 
    } 
} 
0

你可以有:

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 
    } 
} 
相關問題