如何对解析为相同基类型的两种类型使用隐式转换?

How can I use implicit conversions for two types that resolve to the same base type?

type JSON = String
type YAML = String

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

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

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

请注意,类型与其 别名 之间的关系是 equivalence

的关系

If </code> is defined by a type alias <code>type = , then </code> is equivalent to <code>.

这意味着 </code> 和 <code> 所有 上下文中可以互换。当我们定义别名

type JSON = String

那么 String 不是 JSON 的 "base" 类型,而是 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