简体   繁体   English

Scala:隐式解决方案,歧义和矛盾

[英]Scala: Implicit resolution, ambigiuty and contravariance

I have the following piece of Scala with ambigiuous implicits, which I would have thought should work, due to lower priority given to inherited implicits. 我有以下具有模糊隐式的Scala,由于对继承的隐式的优先级较低,因此我认为它应该可以工作。 But it does not - it fails with an ambiguous implicit values -error. 但是,它并不会-会因ambiguous implicit values错误而失败-错误。 Can someone explain to me why priorities does not work here? 有人可以向我解释为什么优先事项在这里不起作用吗?

trait Printer[-T] {
  def prettify(instance:T): String
}

trait LowPriorityPrinter {
  implicit val anyPrinter:Printer[Any] = new Printer[Any]{ def prettify(instance:Any) = instance.toString() }
}

object Printer extends LowPriorityPrinter {
  implicit val intPrinter = new Printer[Int]{ def prettify(instance:Int) = instance.toString() }
}

object MyApp extends App {

  def prettyprint[T](i:T)(implicit p:Printer[T]) = println(p.prettify(i))
  prettyprint(234)

}

The issue is simple, but nasty. 问题很简单,但很讨厌。 The LowPriorityPrinter catch all instance of your type class needs to be generic, not for Any : LowPriorityPrinter捕获类型类的所有实例都是通用的,而不是对于Any

object Printer {
  implicit val intPrinter:    Printer[Int] =
    new Printer[T]{ def prettify(x: T) = x.toString() + " (int") }
  implicit def anyPrinter[T]: Printer[T] =
    new Printer[T]{ def prettify(x: T) = x.toString() + " (general) }
}

Basically, the literal 234 is just as much an Int as it as an Any and neither of those types is more specific than the other (so the priority trick is useless). 基本上,字面量234Any一样,都是一个Int ,并且这两个类型都不比另一个更具体(因此优先级技巧没有用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM