scala - 在 pureconfig 中表示 Either

标签 scala config either hocon pureconfig

我有这样的 HOCON 配置:

[
    {
        name = 1
        url = "http://example.com"
    },
    {
        name = 2
        url = "http://example2.com"
    },
    {
        name = 3
        url = {
            A = "http://example3.com"
            B = "http://example4.com"
        }
    }
]

我想用 pureconfig 解析它。 我如何表示 URL 可以是字符串或多个 URL 的映射,每个 URL 都有一个键?

我试过这个:

import pureconfig.ConfigSource
import pureconfig.generic.auto.exportReader

case class Site(name: Int, url: Either[String, Map[String, String]])
case class Config(sites: List[Site])
ConfigSource.default.loadOrThrow[Config]

但结果是“预期类型 OBJECT。而是找到了 STRING。”

我知道 pureconfig 支持 Option。我没找到支持Either的,是不是可以换成别的东西?

最佳答案

如您所见,Either 不在 types supported out of the box 列表中.

但是 Either 属于 sealed family ,所以:

@ ConfigSource.string("""{ type: left, value: "test" }""").load[Either[String, String]]
res15: ConfigReader.Result[Either[String, String]] = Right(Left("test"))

@ ConfigSource.string("""{ type: right, value: "test" }""").load[Either[String, String]]
res16: ConfigReader.Result[Either[String, String]] = Right(Right("test"))

有效。如果你有一个密封的层次结构,pureconfig 将做的是需要一个具有字段 type 的对象 - 该字段将用于将解析分派(dispatch)到特定的子类型。所有其他字段将作为字段传递以解析为该子类型。

如果这对您不起作用,您可以尝试自己实现编解码器:

// just an example
implicit def eitherReader[A: ConfigReader, B: ConfigReader] =
  new ConfigReader[Either[A, B]] {
    def from(cur: ConfigCursor) =
      // try left, if fail try right
      ConfigReader[A].from(cur).map(Left(_)) orElse ConfigReader[B].from(cur).map(Right(_))
  }

现在不需要区分值:

@ ConfigSource.string("""{ test: "test" }""").load[Map[String, Either[String, String]]]
res26: ConfigReader.Result[Map[String, Either[String, String]]] = Right(Map("test" -> Left("test")))

默认情况下不提供此功能,因为您必须自己回答一些问题:

  • 您如何决定应该使用 Left 还是 Right 解码?
  • Left 后备 RightRight 后备 Left 有意义吗?
  • Either[X, X]怎么样?

如果您知道预期的行为是什么,您可以实现自己的编解码器并在派生中使用它。

关于scala - 在 pureconfig 中表示 Either,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61058354/

相关文章:

scala - 递归创建scala中字符串的所有旋转

java - CompiledScript 的多个实例

python - Spark MapPartitionRDD 无法打印值

java - Scala/Java中 `getClass`方法的用法?

python - 在 ConfigParser 中定义对象值列表

c# - 如何写入主 exe .config 用户设置部分?

haskell - 是否没有标准(任一)monad 实例?

scala - 如何将“Either”列表转换为“Right”值列表?

windows - 配置我的域以指向我的 Windows Vps(没有 plesk 或其他软件)

scala - 为什么我不能从内部的任一投影中提取元组以使用模式匹配进行理解?