(斯卡拉2.11.8)斯卡拉类型类的隐式解析
考虑下面的代码:
object ScalaTest extends App {
class Wrapper {
import Wrapper._
def init(): Unit = {
// "could not find implicit value for parameter tc: ScalaTest.Wrapper.TC[Int]"
printWithTC(123)
// Compiles
printWithTC(123)(IntTC)
// Compiles again!
printWithTC(132)
}
}
object Wrapper {
trait TC[A] {
def text(a: A): String
}
implicit object IntTC extends TC[Int] {
override def text(a: Int) = s"int($a)"
}
def printWithTC[A](a: A)(implicit tc: TC[A]): Unit = {
println(tc.text(a))
}
}
(new Wrapper).init()
}
我有一堆关于这段代码的问题:
- 为什么没有按” t
IntTC
首先得到解决? - 为什么使用一次后编译? (如果您注释掉第一个调用,代码有效)
- 应该将typeclass implicits放在哪里才能正确解析?
我不知道发生了什么,但只是注意到,如果您将对象移到课前,代码也会编译。 – Dima