Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala泛型隐式val_Scala_Generics_Implicit - Fatal编程技术网

Scala泛型隐式val

Scala泛型隐式val,scala,generics,implicit,Scala,Generics,Implicit,我的程序中有很多enum到json转换的隐式val,如下所示: implicit val format = new Format[AuthRoleIndividual] { def reads(json: JsValue) = JsSuccess(AuthRoleIndividual.withName(json.as[String])) def writes(myEnum: AuthRoleIndividual) = JsString(myEnum.toString) }

我的程序中有很多enum到json转换的隐式val,如下所示:

implicit val format = new Format[AuthRoleIndividual] {
    def reads(json: JsValue) = JsSuccess(AuthRoleIndividual.withName(json.as[String]))
    def writes(myEnum: AuthRoleIndividual) = JsString(myEnum.toString)
  }
implicit val format[T <: Enumeration] = new Format[T] {
    def reads(json: JsValue) = JsSuccess(T.withName(json.as[String]))
    def writes(myEnum: T) = JsString(myEnum.toString)
  }
注意:
AuthRoleIndividual
扩展了
枚举
。我的方法是这样写:

implicit val format = new Format[AuthRoleIndividual] {
    def reads(json: JsValue) = JsSuccess(AuthRoleIndividual.withName(json.as[String]))
    def writes(myEnum: AuthRoleIndividual) = JsString(myEnum.toString)
  }
implicit val format[T <: Enumeration] = new Format[T] {
    def reads(json: JsValue) = JsSuccess(T.withName(json.as[String]))
    def writes(myEnum: T) = JsString(myEnum.toString)
  }

隐式val格式[T首先,您误解了
枚举
值的类型,对于
枚举
值,的类型是
类型而不是
枚举
,因此您应该为
类型绑定
隐式
。例如:

  object State extends Enumeration {
    val A = Value("A")
    val B = Value("B")
  }

  implicit def foo(v: State.Value): String = v.toString + "-Bar"

  val t: String = State.A

其次,正如上面的代码一样,由于
类型绑定到
对象
State.Value
),因此您无法按照Play JSON已经提供的方式为所有
枚举

创建泛型隐式,对于枚举,非常感谢您的澄清!