类树的隐式转换

时间:2016-06-30 13:36:15

标签: scala

我有一组特征/类,如:

trait Parent
case class ChildA(str: String) extends Parent
case class ChildB(str: String) extends Parent

object Parent {
   implicit def toA(str: String) = ChildA(str)
   implicit def toB(str: String) = ChildB(str)
}

这适用于ChildAChildB转换的情况。

在我的测试中,我希望有一个额外的规则,即如果方法收到Parent,它会执行以下操作:

implicit def toParent(str: String) = ChildA(str)

我该怎么做?编译器似乎感到困惑,因为它可以选择多次转换为Parent。

1 个答案:

答案 0 :(得分:2)

如果您想要toA选择toB来转换为Parent,您可以使用隐式优先级机制。如果隐式从类或特征继承,则隐含优先级较低。

scala> :paste
// Entering paste mode (ctrl-D to finish)

trait Parent
case class ChildA(str: String) extends Parent
case class ChildB(str: String) extends Parent

trait LowerPiorityImplicits {
  implicit def toB(str: String) = ChildB(str)
}

object Parent extends LowerPiorityImplicits {
   implicit def toA(str: String) = ChildA(str)
}

// Exiting paste mode, now interpreting.

warning: there were two feature warnings; re-run with -feature for details
defined trait Parent
defined class ChildA
defined class ChildB
defined trait LowerPiorityImplicits
defined object Parent

scala> val foo: ChildA = "foo"
foo: ChildA = ChildA(foo)

scala> val foo: ChildB = "foo"
foo: ChildB = ChildB(foo)

scala> val foo: Parent = "foo"
foo: Parent = ChildA(foo)