Reputation: 6006
I have a function foo
declared in Bar
object:
package test
object Bar{
def foo[T : A](b: T) = println(b)
def main(args: Array[String]) {
foo(3)
}
}
where A
is declared in the same package:
sealed trait A[T]
object A {
implicit object AInt extends A[Int]
implicit object AString extends A[String]
}
in this configuration Bar object doesn't compile and produces this error message:
could not find implicit value for evidence parameter of type test.A[Int]
foo(3)
^
But when I place trait A
and its companion object into package object test
all work fine. Why?
EDIT
The problem is in order of declaration. If I place A
typeclass declaration before Bar
declaration everything works fine.
Upvotes: 2
Views: 1081
Reputation: 67330
So the two solutions seem to be:
(1) Declare A
first:
sealed trait A[T]
object A {
implicit object AInt extends A[Int ]
implicit object AString extends A[String]
}
object Bar {
def foo[T: A](b: T) = println(b)
def main(args: Array[String]): Unit = foo(3)
}
(2) Use def
or val
with given return type:
object Bar {
def foo[T: A](b: T) = println(b)
def main(args: Array[String]): Unit = foo(3)
}
sealed trait A[T]
object A {
implicit def aInt : A[Int ] = AInt
implicit def aString: A[String] = AString
private object AInt extends A[Int ]
private object AString extends A[String]
}
I would consider this is a compiler bug, but at least you can work around it.
Upvotes: 3