1

请参考下面的源代码。所有源代码都定义在同一个包中。当我在单个源文件中定义所有代码ShowMain.scala时,我得到一个编译错误,但是当object ShowMainShowMain.scalatrait Showobject 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]
4

1 回答 1

9

有一条规则必须在编译单元的早期定义隐式。

因此,将对象 Show 移到顶部并编译。

或者,

object Show {
  //implicit object StringShow extends Show[String] {
  implicit val x: Show[String] = new Show[String] {
    def show(s: String) = s"[String: $s]"
  }
}

请参阅有关类型的说明:

https://stackoverflow.com/a/2731285/1296806

于 2014-08-24T05:08:13.663 回答