Scala推断更高的kinded类型与证据

时间:2015-02-27 08:40:13

标签: scala

我正在尝试提供一些涉及更高kinded类型的类型类实现,如下面的代码所示:

trait Blah[A,B] {
  def apply(b:B):List[A]
}

object Blah {
  implicit def blah1[A,B<:List[A]]:Blah[A,B] = new Blah[A,B]{
    def apply(b:B):List[A] = b
  }

  implicit def blah2[A,B](implicit ev: B<:<List[A]):Blah[A,B] = new Blah[A,B]{
    def apply(b:B):List[A] = b
  }
}

object Stuff {

  def method[A,B](b:B)(implicit blah:Blah[A,B]):List[A] = {
    blah(b)
  }

  method(List(2,3))
}

如果我删除方法Blah.blah2,编译器会失败,因为它无法解析隐式。为什么第二种形式(使用隐式证据)会起作用,何时应该使用?

1 个答案:

答案 0 :(得分:1)

嗯......因为它无法推断出正确的类型,因为第一个implicit blah1期望AB之间的关系。

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

trait Blah[A,B] {
  def apply(b:B):List[A]
}

object Blah {
  implicit def blah1[A,B<:List[A]]:Blah[A,B] = new Blah[A,B] {
    def apply(b:B):List[A] = b
  }
}

def method[A,B](b:B)(implicit blah:Blah[A,B]):List[A] = {
  blah(b)
}

// Exiting paste mode, now interpreting.

defined trait Blah
defined object Blah

method: [A, B](b: B)(implicit blah: Blah[A,B])List[A]

scala> method( List( 4, 5) )
<console>:37: error: could not find implicit value for parameter blah: Blah[A,List[Int]]
              method( List( 4, 5) )
                    ^

请参阅...查找implicit类型的Blah[ A, List[ Int ] ]

我们只需要对类型进行帮助就可以了,

scala> method[ Int, List[ Int] ]( List( 3, 4, 5 ) )
res1: List[Int] = List(3, 4, 5)
相关问题