How to declare traits as taking implicit “constructor parameters”?

Actually, I’ve wanted this quite often before, but just came up with this idea. You can translate

trait T(implicit impl: ClassName) {
  def foo = ... // using impl here
}

to [EDITED: original version didn’t provide access to implicit for other methods]

trait T {
  // no need to ever use it outside T
  protected case class ClassNameW(implicit val wrapped: ClassName)

  // normally defined by caller as val implWrap = ClassNameW 
  protected val implWrap: ClassNameW 

  // will have to repeat this when you extend T and need access to the implicit
  import implWrap.wrapped

  def foo = ... // using wrapped here
}

Leave a Comment