2015-06-11 34 views
2

我有點困惑,爲什麼下面的代碼不工作:Scala的通用功能......在功能使用T-

implicit val connectReads: Reads[ConnectCommand] = (
    (JsPath \ "uuid").read[String] 
    )(ConnectCommand.apply _) 

    private def generateMessage[T](json: JsValue) = json.validate[T] match { 
    case s: JsSuccess[T] => s.asOpt 
    case e: JsError => None 
    } 

的功能將被稱爲如下:

generateMessage[ConnectCommand](json) 

我得到以下錯誤:

Error:(59, 64) No Json deserializer found for type T. Try to implement an implicit Reads or Format for this type. 
    private def generateMessage[T](json: JsValue) = json.validate[T] match { 
                  ^
Error:(59, 64) not enough arguments for method validate: (implicit rds: play.api.libs.json.Reads[T])play.api.libs.json.JsResult[T]. 
Unspecified value parameter rds. 
    private def generateMessage[T](json: JsValue) = json.validate[T] match { 
                 ^

我是相當新的Scala仿製藥...有什麼辦法做我想在這裏做什麼?

+1

Cay S. Horstman撰寫的'不耐煩的斯卡拉'在關於暗示方面有很好的篇章,但是可能很難在不閱讀前面的章節的情況下跳入其中。 –

+0

感謝您的提示!我其實讀過那本書的一半......太棒了。我想是時候閱讀下半場了! – threejeez

+1

我發現這個練習非常有用 - 有些花了很多時間,在後面的章節中遇到了很多困難。 https://github.com/BasileDuPlessis/scala-for-the-impatient提供了一整套完整的高質量解決方案。最好先開發自己的解決方案,然後看看Basile是如何做到的,以便學習另一種方法。 –

回答

3

根據文檔JsValue.validate需要一個隱含的Reads你的類型是可用:

def validate[T](implicit rds: Reads[T]): JsResult[T] 

假設你有它可在您致電generateMessage的地方,你必須把它傳遞到generateMessage,讓validate會看到它還有:

private def generateMessage[T](json: JsValue)(implicit rds: Reads[T]) 

或較短的形式:

private def generateMessage[T : Reads](json: JsValue) 
+0

感謝您的回覆......那麼如何調用generateMessage? – threejeez

+0

@threejeez如果您在調用generateMessage時有適當的隱式「Reads」,則沒有其他更改。 – Kolmar

1

這不是真的與泛型相關,而是蘊含其中,以及庫如何要求您定義implicits類型並導入它們。

這是必需的,因爲validate函數不知道您的JsValue的格式,因此要求implicit scope提供一個。然後它使用該格式來驗證它。它起初很混亂,但最終更好,因爲當需要JSON格式時,您不必爲每個方法調用明確提供格式。

此外,這些是兩行送人錯誤消息:

Try to implement an implicit Reads or Format for this type. 

not enough arguments for method validate: (implicit rds: play.api.libs.json.Reads[T]) 

我們看到,您可能需要進口隱含Format/Reads或定義一個自己。你可以閱讀如何做到這一點in the relevant section of the Play! documentation

編輯:

你的方法缺少隱含參數(implicit reads: Reads[T])到它傳遞到validate功能:

private def generateMessage[T](json: JsValue)(implicit reads: Reads[T]) = json.validate[T] match { 
case s: JsSuccess[T] => s.asOpt 
case e: JsError => None 
} 
+0

感謝您的回覆。我實際上已經完成了我的功能之上。我編輯了我的問題以顯示它。 – threejeez