The problem is that your Int int not in the implicit scope at the moment you call the function:
(new Impl).f
The compiler will not look inside the class for implicits used when calling other members of this class.
You can use the Chris solution, or you can:
val newImpl = newImpl import newImpl.int newImpl.f
Or ... If you want the value inside the class to be the default, but it has the ability to override it from the outside, then implicit parameters can also be default parameters:
trait Api { def defaultInt: Int def f(implicit a: Int = defaultInt) = ??? } class Impl extends Api { val defaultInt = 2 }
UPDATE
Based on the commentary on your own answer, implicit chaining is also implied, which is possible here:
trait HasInt { def intVal: Int } sealed trait HasIntTypeClass[T] extends HasInt implicit object StringHasInt extends HasIntTypeClass[String] { val intVal = 42 } trait Api { def defaultHasInt: HasInt def f(implicit a: HasInt = defaultHasInt): Int = a.intVal * 2 } class Impl extends Api { def defaultHasInt: HasInt = implicitly[HasIntTypeClass[String]] }
In any case, put the type parameter on defaultHasInt , if necessary.
source share