gpt4 book ai didi

scala - 在 pureconfig 中表示 Either

转载 作者:行者123 更新时间:2023-12-04 16:40:50 33 4
gpt4 key购买 nike

我有这样的 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com