【问题标题】:Why can't Scala find my typeclass instance defined implicitly in the companion object, when the typeclass is not in a dedicated source file?当类型类不在专用源文件中时,为什么 Scala 找不到我在伴随对象中隐式定义的类型类实例?
【发布时间】: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


    【解决方案1】:

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

    所以,将对象 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

    【讨论】:

    • 感谢您对类型归属的后续评论,我注意到这是使 val 工作的唯一方法,并且将为该案例创建第二个问题。
    • 了解类型归属要求回答了我关于编译器能够找到我的隐含项的许多其他问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-08-24
    • 2019-07-21
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    相关资源
    最近更新 更多