scala 纯配置枚举

rfbsl7qr  于 5个月前  发布在  Scala
关注(0)|答案(1)|浏览(78)

纯配置无法解析conf中的大写字母

sealed trait Occupation extends Product with Serializable

  object Occupation {
    case class Employed(job: String) extends Occupation

    object Employed {
      implicit val employedReader = deriveReader[Employed]
    }

    case object Unemployed extends Occupation {
      implicit val unemployedReader = deriveReader[Unemployed.type]
    }

    case object Student extends Occupation {
      implicit val studentReader = deriveReader[Student.type]
    }

    implicit val occupationReader = deriveReader[Occupation]
  }

  case class WorkingPerson(name: String, surname: String, occupation: Occupation)

  val res = ConfigSource.string("{ name: Isaac, surname: Newton, occupation.type: student }").load[WorkingPerson]

字符串
它可以工作,但我需要像'StudenT'这样的枚举值,如果我这样做,我会得到“ConvertFailure(UnexpectedValueForFieldCoproductHint(Unquoted(“student”))”

6rvt4ljy

6rvt4ljy1#

如果你想改变how the field is being read,你需要提供一个hint
对于密封族,PureConfig提供了一种自定义转换的方法,而无需替换默认的ConfigReader。通过在该密封族的作用域中放置CoproductHint的示例,我们可以自定义如何消除歧义。例如,如果type与case类选项的某个字段冲突,我们可以使用另一个字段。

import pureconfig.generic.FieldCoproductHint
implicit val animalConfHint = new FieldCoproductHint[AnimalConf]("kind")

字符串
FieldCoproductHint也可以用不同的方式写类名。首先,在隐式作用域中定义一个新的FieldCoproductHint

implicit val animalConfHint = new FieldCoproductHint[AnimalConf]("type") {
  override def fieldValue(name: String) = name.dropRight("Conf".length)
}


在本例中,需要添加FieldCoproductHint[Occupation]

implicit val occupationConfHint = new FieldCoproductHint[Occupation]("type") {
  override def fieldValue(name: String) = name
}


我创建了一个working example in scastie
你真的需要使用半自动推导吗?你可以得到相同的结果,只是使用自动的。
这里是working example in scatsie

  • build.sbt
libraryDependencies += "com.github.pureconfig" %% "pureconfig" % "0.14.0"

  • main.scala
import pureconfig._
import pureconfig.generic.FieldCoproductHint
import pureconfig.generic.auto._

sealed trait Occupation extends Product with Serializable

implicit val occupationConfHint = new FieldCoproductHint[Occupation]("type") {
  override def fieldValue(name: String) = name
}

object Occupation {
  case class Employed(job: String) extends Occupation
  case object Unemployed extends Occupation
  case object StudenT extends Occupation
}

case class WorkingPerson(name: String, surname: String, occupation: Occupation)

val res = ConfigSource.string("{ name: Isaac, surname: Newton, occupation.type: StudenT }").load[WorkingPerson]
println(res)

相关问题