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

后端 未结 5 2048
孤街浪徒
孤街浪徒 2020-12-23 16:45

I\'m designing a class hierarchy, which consists of a base class along with several traits. The base class provides default implementations of several methods, and the trai

5条回答
  •  盖世英雄少女心
    2020-12-23 17:19

    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
    }
    

提交回复
热议问题