Why can't Scala find my typeclass instance implicitly in a companion object when the type class is not in the selected source file?

Refer to the source code below. All source code is defined in one package. When I define all the code in the same ShowMain.scala source file, I get a compilation error, however, when the object ShowMain defined in ShowMain.scala and the trait Show and object Show defined in Show.scala , there is a compilation error.

My question is: What is the reason for this? What language rule do I follow?

Code example:

 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]" } } 

Compilation Error:

(ScalaIDE / Scala 2.11.2 on a 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] 
+1
source share
1 answer

There is a rule that must be implicitly defined earlier in the compilation unit.

So, move the Show object up and compiles.

As an alternative,

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

see type explanation:

fooobar.com/questions/392108 / ...

+9
source

Source: https://habr.com/ru/post/974404/


All Articles