【问题标题】:How can I use implicit conversions for two types that resolve to the same base type?如何对解析为相同基类型的两种类型使用隐式转换?
【发布时间】:2019-12-23 22:46:31
【问题描述】:
type JSON = String
type YAML = String

implicit def json2yaml(in:JSON):YAML = "some conversion"

val js:JSON = "some json"
val yml: YAML = js

上面的代码将“一些 json”分配给 yml。不使用隐式转换。那是因为 YAML 和 JSON 都解析为字符串吗?有没有办法鼓励代码进行转换?

【问题讨论】:

  • 直接这样 - 不,但当然你总是可以将它们包装到带有字符串参数的案例类中并轻松完成
  • 隐式转换是一种不好的做法,现在从相同的两种类型转换似乎是使代码难以理解的好方法。只添加一个toYaml 扩展方法有什么问题?

标签: scala implicit-conversion implicit type-alias


【解决方案1】:

注意类型和它的别名之间的关系是equivalence

如果? 由类型别名type ? = ? 定义,则? 是 相当于?

这意味着??所有 上下文中可以互换。当我们定义别名时

type JSON = String

那么String 不是JSON 的“基本”类型,而是 JSON 本身。因此

implicit def json2yaml(in: JSON): YAML = "some conversion"

等价于

implicit def json2yaml(in: String): String = "some conversion"

这就是隐式转换不会发生的原因。

考虑像这样的扩展方法方法,而不是隐式转换(这往往是不鼓励的)

case class Json(v: String)
case class Yaml(v: String)

implicit class JsonToJaml(json: Json) {
  def asYaml: Yaml = Yaml("some conversion which uses ${json.v}")
}

val js: Json = Json("some json")
val yml: Yaml = js.asYaml

【讨论】:

    猜你喜欢
    • 2019-03-20
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    相关资源
    最近更新 更多