当typeclass不在专用的源文件中时,为什么Scala不能在同伴对象中隐式定义我的typeclass实例? [英] Why can't Scala find my typeclass instance defined implicitly in the companion object, when the typeclass is not in a dedicated source file?
问题描述
请参考下面的源代码.所有源代码都在同一包中定义.当我在单个源文件ShowMain.scala
中定义所有代码时,会出现编译错误,但是,当object ShowMain
在ShowMain.scala
中定义并且trait Show
和object Show
在Show.scala
中定义时,没有编译错误.
Please refer to the source code below. All source code is defined in the same package. When I define all of the code within a single source file ShowMain.scala
, I get a compile error, however when object ShowMain
is defined in ShowMain.scala
and trait Show
and object Show
are defined in Show.scala
, there is no compile error.
我的问题:原因是什么?我违反了什么语言规则?
My question: What is the cause for this? What language rule have I run afoul of?
示例代码:
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]"
}
}
编译错误:
(包含output("hello")
的行上的ScalaIDE/Scala 2.11.2)
(ScalaIDE/Scala 2.11.2 on line containing 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]
推荐答案
有一个规则,必须在编译单元中较早地定义隐式.
There's a rule that implicit has to be defined earlier in the compilation unit.
因此,将对象Show移到顶部并编译.
So, move object Show to the top and it compiles.
或者,
object Show {
//implicit object StringShow extends Show[String] {
implicit val x: Show[String] = new Show[String] {
def show(s: String) = s"[String: $s]"
}
}
请参阅有关类型的说明:
see the explanation about the type:
https://stackoverflow.com/a/2731285/1296806
这篇关于当typeclass不在专用的源文件中时,为什么Scala不能在同伴对象中隐式定义我的typeclass实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!