Search code examples
scalatraitsself-typecake-pattern

Expose protected member as public with self tyes


I have a trait that representing some module that exposes some public method (think of a service):

trait X { 
  def exposeMe: AService = ...
  def keepMeHidden: BService = ...
}

Then, I have a Y module that requires services from X. Clients of Y also need one service from X. But I don't want them to depend on whole X, just on this one service. I would like to like "export" that one service to be public.

trait Y { this: X => 
  def exposeMe2: AService = exposeMe
}

This works, but is there a way to keep the method name the same?


Solution

  • Short answer:

    trait X { 
      def exposeMe: Int = 12
      def keepMeHidden: Int = 41
    }
    
    trait XComponent {
      def x: X
    }
    
    trait Y { this: XComponent => 
      def exposeMe: Int = x.exposeMe
    }
    

    Update after question edition.

    Problem is that you baked half of cake and then want to extract a layer from this complex component. Right way is to require what you really need:

    trait Y { this: AServiceComp => 
      def exposeMe: AService = aService.exposeMe
    }
    

    Where AServiceComp implementation could be made with single AService implementation or using new XImpl.exposeMe (imho the last is bizarre).