代码之家  ›  专栏  ›  技术社区  ›  Simon

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

  •  0
  • Simon  · 技术社区  · 7 年前

    我有一个特点 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
    }
    

    有可能做到这一点吗?

    3 回复  |  直到 7 年前
        1
  •  1
  •   dkim    7 年前

    A. protected 只能从定义成员的类的子类访问成员:

    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()
               ^
    
        2
  •  1
  •   acopeland    7 年前

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

    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 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
    }
    
        3
  •  0
  •   S.Karthik    7 年前

    使用[此]限制受保护的方法,如

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