簡體   English   中英

什么是 Scala 3 相當於這個 Scala 2 使用枚舉和 play-json 的代碼?

[英]What is Scala 3 equivalent to this Scala 2 code that uses Enumeration and play-json?

我有一些在 Scala 2.{10,11,12,13} 中工作的代碼,我現在正在嘗試將其轉換為 Scala 3. Scala 3 的枚舉方式不同於 Scala 2. 我正在嘗試找出如何轉換以下代碼與play-json交互,以便它可以與 Scala 一起使用 3. 任何提示或指針指向已經跨過此橋的項目的代碼?

// Scala 2.x style code in EnumUtils.scala 
import play.api.libs.json._
import scala.language.implicitConversions

// see: http://perevillega.com/enums-to-json-in-scala
object EnumUtils {
  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] =
    new Reads[E#Value] {
      def reads(json: JsValue): JsResult[E#Value] = json match {
        case JsString(s) => {
          try {
            JsSuccess(enum.withName(s))
          } catch {
            case _: NoSuchElementException =>
              JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not appear to contain the value: '$s'")
          }
        }
        case _ => JsError("String value expected")
      }
    }
  implicit def enumWrites[E <: Enumeration]: Writes[E#Value] = new Writes[E#Value] {
    def writes(v: E#Value): JsValue = JsString(v.toString)
  }
  implicit def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(EnumUtils.enumReads(enum), EnumUtils.enumWrites)
  }
}
// ----------------------------------------------------------------------------------
// Scala 2.x style code in Xyz.scala
import play.api.libs.json.{Reads, Writes}

object Xyz extends Enumeration {
  type Xyz = Value
  val name, link, unknown = Value
  implicit val enumReads: Reads[Xyz] = EnumUtils.enumReads(Xyz)
  implicit def enumWrites: Writes[Xyz] = EnumUtils.enumWrites
}

作為一個選項,您可以切換到jsoniter-scala

它開箱即用地支持 Scala 2 和 Scala 3 的枚舉。

它還可以方便地派生出安全高效的 JSON 編解碼器。

只需要將所需的庫添加到您的依賴項中:

libraryDependencies ++= Seq(
  // Use the %%% operator instead of %% for Scala.js and Scala Native 
  "com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-core"   % "2.13.5",
  // Use the "provided" scope instead when the "compile-internal" scope is not supported  
  "com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-macros" % "2.13.5" % "compile-internal"
)

然后導出一個編解碼器並使用它:

import com.github.plokhotnyuk.jsoniter_scala.core._
import com.github.plokhotnyuk.jsoniter_scala.macros._

implicit val codec: JsonValueCodec[Xyz.Xyz] = JsonCodecMaker.make

println(readFromString[Xyz.Xyz]("\"name\""))

順便說一句,您可以在 Scastie 上運行完整代碼: https://scastie.scala-lang.org/Evj718q6TcCZow9lRhKaPw

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM