2017-08-17 14 views
1

Ich habe eine Menge von impliziten val für ENUM json Transformationen in meinem Programm wie folgt aus:Scala generic implizite val

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

Hinweis: AuthRoleIndividual erstreckt Enumeration. Mein Ansatz war, so etwas zu schreiben:

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

Aber das ist nicht möglich. Irgendwelche Ideen?

+1

Nebenbei bietet Play JSON bereits ['Writes'] (https://www.playframework.com/documentation/2.6.0/api/scala/index.html#play.api.libs.json.Writes$ @enumNameWrites [E% 3C: Enumeration]: play.api.libs.json.Writes [E # Wert]) und ['Read's] (https://www.playframework.com/documentation/2.6.0/api/ scala/index.html#[email protected] [E% 3C: Enumeration] (enum: E): play.api.libs.json.Reads [E # Wert]) für Enumerationen – cchantep

Antwort

1

Erstens Du Missverständnis der Typ des Enumeration Wert, für Enumeration Wert, die Wert ‚s-Typ ist Value Typ nicht Enumeration, so dass Sie die implicit für Value Typ binden sollte. Zum Beispiel:

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 

zweitens die obigen Code Da der Value Typ der object (State.value) binden, können Sie nicht generic implicits für alle Enumeration erstellen.

+0

Danke sehr zur Klärung! – perotom