【发布时间】:2014-11-10 23:22:51
【问题描述】:
请参考下面的源代码。所有源代码都定义在同一个包中。当我在单个源文件ShowMain.scala 中定义所有代码时,我得到一个编译错误,但是当object ShowMain 在ShowMain.scala 和trait Show 和object Show 在Show.scala 中定义时,有没有编译错误。
我的问题:这是什么原因?我违反了什么语言规则?
示例代码:
object ShowMain {
def main(args: Array[String]): Unit = {
output("hello")
}
def output[A](a: A)(implicit show: Show[A]) =
println(show.show(a))
}
trait Show[-A] {
def show(a: A): String
}
object Show {
implicit object StringShow extends Show[String] {
def show(s: String) = s"[String: $s]"
}
}
编译错误:
(ScalaIDE/Scala 2.11.2 上线包含output("hello"))
Multiple markers at this line
- not enough arguments for method output: (implicit show: test.typeclasses.show1.Show[String])Unit. Unspecified value
parameter show.
- not enough arguments for method output: (implicit show: test.typeclasses.show1.Show[String])Unit. Unspecified value
parameter show.
- could not find implicit value for parameter show: test.typeclasses.show1.Show[String]
- could not find implicit value for parameter show: test.typeclasses.show1.Show[String]
【问题讨论】:
标签: scala typeclass implicit companion-object