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

后端 未结 5 2046
孤街浪徒
孤街浪徒 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:06

    This isn't possible.

    But you can use implicitly and Scala's type inference to make this as painless as possible.

    trait MyTrait {
    
        protected[this] implicit def e: ClassName
    
    }
    

    and then

    class MyClass extends MyTrait {
    
        protected[this] val e = implicitly // or def
    
    }
    

    Succinct, and doesn't even require writing the type in the extending class.

提交回复
热议问题