Scala:是否可以将对特征的函数定义的访问限制为其直接调用者?

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

我有一个特质LoggerHelper。在里面我有一些函数定义。我希望它们可以通过扩展此特性的 类 访问,但我想限制 类 的访问,注入 类 扩展此特性。

示例:

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

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

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

有可能实现吗?

protected 成员只能从 class 的子 class 访问,其中定义了成员:

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()
           ^

用[this]限制受保护的方法,比如

trait LoggerHelper {
  protected[this] def log() = ???
}

使用 protected[this] 保护的成员只能从 class 的 this 实例及其子 class 实例访问。

class Base{
    protected val alpha ="Alpha";
    protected[this] def sayHello = "Hello";
    def foo = Console println(new Base().sayHello) // won't compile
    def bar = Console println(this.sayHello)
}
class Derived extends Base{
    def hello = println(this.sayHello) ;
    //def hello2 = println((new Derived() .sayHello) // won't compile
}

使用 protected 保护的成员可以从定义该成员的 class 的任何实例以及它们的子classes 访问。

class Base{
    protected val alpha ="Alpha";
    protected def sayHello = "Hello";
}
class Derived extends Base{
    def hello = println(this.sayHello);
    def hello2 = println((new Derived()).sayHello); // has access to sayHello() in the original instance
}