【发布时间】:2017-05-31 21:04:21
【问题描述】:
(斯卡拉 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()
}
我有很多关于这段代码的问题:
- 为什么
IntTC不首先得到解决? - 为什么使用一次就可以编译? (如果您注释掉第一次调用,代码可以工作)
- 类型类隐式应该放在哪里才能正确解析?
【问题讨论】:
-
我不知道发生了什么,但只是注意到,如果你将对象移动到课堂之前,代码也会编译。