Search code examples
scaladependency-injectionguicetraits

Scala: is it possible to restrict access to the function definitions of a trait to its direct callers?


I have a Trait LoggerHelper. Inside I have some function definitions. I want them to be accessible by the classes extending this trait but I would like to restrict the access for the classes injecting the classes extending this trait.

Example:

Trait LoggerHelper {
  def log() = ???
} 

Class A extends LoggerHelper {
  log() //OK
}

Class B @Inject() (a: A) {
  a.log() //I want this line does not compile
}

Is it possible to achieve this?


Solution

  • A protected member can be accessed only from subclasses of the class where the member is defined:

    scala> trait LoggerHelper {
         |   protected def log() = ???
         | }
    defined trait LoggerHelper
    
    scala> class A extends LoggerHelper {
         |   log()
         | }
    defined class A
    
    scala> class B(a: A) {
         |   a.log()
         | }
    <console>:13: error: method log in trait LoggerHelper cannot be accessed in A
     Access to protected method log not permitted because
     enclosing class B is not a subclass of
     trait LoggerHelper where target is defined
             a.log()
               ^