【问题标题】:When should you use access modifiers for type members?什么时候应该对类型成员使用访问修饰符?
【发布时间】:2016-10-02 10:05:32
【问题描述】:
class EG {
  private[this] type TypeMember = A
  private[this] var field: Int = 0
}

可以像字段一样为类型成员指定访问修饰符。众所周知,在 OOP 的情况下,encapsulation of fields 确实提供了防止意外共享状态和限制状态修改的好处。据我所知,类型成员只能在 Scala 中找到,并且在许多地方它们只是被定义为公共的,因此在类型成员上使用访问修饰符并不像在字段的情况下那样被很好地理解。类型成员不持有任何状态,如变量或字段。由于它不包含值,因此无法对其进行变异。 所以我的问题是您应该在哪些地方限制对类型成员的访问(将类型成员定义为私有或受保护)?

【问题讨论】:

    标签: scala oop encapsulation type-members


    【解决方案1】:

    在不提供定义的情况下将类型成员声明设为私​​有不仅没用而且编译器也不允许

    scala> class Foo { private[this] type T }
    <console>:11: error: abstract member may not have private modifier
           class Foo { private[this] type T }
    

    如果您改为定义类型成员,那么可能会有一些合法的用例。

    示例,私有类型别名:

    trait Foo {   
      private[this] type T = String
    }
    

    在这种情况下,T 类型只存在于类中。仅在实现的上下文中为类型提供较短的名称可能很有用。

    另一个例子,类型参数的私有重命名

    trait Foo[Key] {
      private[this] type K = Key
    }
    

    使用大致相同的用例。

    关于使其受到保护,这也可能是有道理的。示例:

    trait Foo {
      protected[this] type V
    
      def foo(v: V): V
    }
    

    它定义了一个接口,该接口由一个在尚未指定的类型V上工作的方法组成,然后:

    class Bar extends Foo {
      type V = String // actually defining the type
      def foo(v: V): V = v 
    }
    

    【讨论】:

    • 以上仅用于说明目的。可以是private[this] type TypeMember = Aprivate[this] type TypeMember &lt;: Aprivate type TypeMember = Aprotected[this] type TypeMember = Aprotected type TypeMember = A 只是为了举例说明。
    猜你喜欢
    • 2014-01-02
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多