Why can't Scala find my typeclass instance defined implicitly in the companion object, when the typeclass is not in a dedicated source file?

前端 未结 1 2018
情深已故
情深已故 2020-12-12 03:21

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

1条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 03:55

    There's a rule that implicit has to be defined earlier in the compilation unit.

    So, move object Show to the top and it compiles.

    Alternatively,

    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

    0 讨论(0)
提交回复
热议问题