简体   繁体   English

Scala模式与类型类的类型参数匹配

[英]Scala pattern match with type parameter of type class

sealed trait FormField
case class StringField(name: String, value: String) extends FormField
case class ChoiceField[T : Writes](name: String, value: T, choices: List[T]) extends FormField

and then, somewhere else I need to do this: 然后,在其他地方我需要这样做:

def makeJson(fields: List[FormField]) = fields.map {
   case StringField(name, value) => Json.obj(name -> value)
   case ChoiceField(name, value, _) => Json.obj(name -> value)
}

In that last function, scalac/sbt doesn't "understand" that value is convertable to json (through its implicit / type class Writes[T] ). 在最后一个函数中,scalac / sbt不能“理解”该value可转换为json(通过其隐式/类型类Writes[T] )。 How can I write it so that it "gets it"? 我如何编写它以使其“得到它”?

(Note: Writes[T] is from Play Framework - it basically says that there is an implicit conversion avaiable for the type T => JsValue ) (注意: Writes[T]来自Play框架-它基本上说类型T => JsValue有隐式转换)

Your problem is that the Writes implicit is not in scope when you do pattern matching; 您的问题是,进行模式匹配时,隐式Writes不在作用域内; the easiest solution would be to keep an explicit reference to it so that you can use it when needed. 最简单的解决方案是保留对其的明确引用,以便您可以在需要时使用它。 That way your class definition becomes something like: 这样,您的类定义将变为:

case class ChoiceField[T](name: String, value: T, choices: List[T])(implicit val writes: Writes[T]) extends FormField

And your pattern match: 和您的模式匹配:

case cf @ ChoiceField(name, value, _) =>
  implicit val tWrites = cf.writes
  Json.obj(name -> value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM