type JSON = String
type YAML = String
implicit def json2yaml(in:JSON):YAML = "some conversion"
val js:JSON = "some json"
val yml: YAML = js
上面的代码为yml分配了“ some json”。不使用隐式转换。那是因为YAML和JSON都解析为String吗?有没有办法鼓励代码进行转换?
请注意,类型与其alias之间的关系是equivalence的关系>>
上下文中是可互换的。当我们定义别名如果
𝑡
由类型别名type 𝑡 = 𝑇
定义,则𝑡
为等效于𝑇
。这意味着
𝑡
和𝑇
在all
type JSON = String
然后
String
不是JSON
的“基本”类型,而是是
JSON
本身。因此implicit def json2yaml(in: JSON): YAML = "some conversion"
等效于
implicit def json2yaml(in: String): String = "some conversion"
这就是为什么不进行隐式转换的原因。
而不是隐式转换(通常不鼓励这样做),请考虑extension method
这样的方法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