【发布时间】:2012-03-09 13:14:01
【问题描述】:
我发现使用和定义隐式值的行为非常奇怪(scala 2.9.1),想知道是否有人可以解释它,或者它是否是 scala 错误?
我创建了一个独立的示例:
object AnnoyingObjectForNoPurpose {
trait Printer[T] {
def doPrint(v: T): Unit
}
def print[T : Printer](v: T) = implicitly[Printer[T]].doPrint(v)
trait DelayedRunner extends DelayedInit {
def delayedInit(x: => Unit){ x }
}
// this works, as it should
object Normal extends DelayedRunner {
implicit val imp = new Printer[Int] {
def doPrint(v: Int) = println(v + " should work")
}
print(343)
}
// this compiles, but it shouldn't
// and won't run, cause the implicit is still null
object FalsePositive extends DelayedRunner {
print(123)
implicit val imp = new Printer[Int] {
def doPrint(v: Int) = println(v + " should not compile")
}
}
def main(args: Array[String]) {
implicit val imp = new Printer[Int] {
def doPrint(v: Int) = println(v + " should work")
}
print(44)
// print(33.0) // correctly doesn't work
Normal // force it to run
FalsePositive // force this to run too
}
}
【问题讨论】:
-
我觉得很困惑,你在 def print(第 7 行)中重用 T 作为标识符,这导致了一个问题,
implicitly [Printer [T]]是隐含的打印机打印机吗?在这里使用不同的标识符是否有助于避免混淆? -
@userunknown 我不太清楚你的意思,或者更简单的写法?
-
您能更具体地谈谈您的问题吗?你说“这可以编译,但它不应该”之类的话,但这是一个陈述,而不是一个问题。你的问题是什么?
标签: scala