When should access modifiers be used for type members?

class EG {
  private[this] type TypeMember = A
  private[this] var field: Int = 0
}

You can specify access modifiers for type members as fields. In the case of OOP, it is well understood that encapsulation fields provide an advantage that prevents inadvertent state sharing and the restriction of state modification. As far as I know, type members are found only in Scala, and in many places they are simply defined as public, so using access modifiers for type members is not as well understood as in the case of fields. Type members have no state, like a variable or field. Since it does not matter, it cannot be mutated. So my question is, which places should you restrict access to a type member (define a type member as private or secure)?

+4
source share
1 answer

Creating a member of type Private declaration without providing a definition is not only useless, but also not allowed by the compiler

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

If you define a type member instead, then there may be some legitimate use cases.

Example: private type alias:

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

In this case, the type Texists only inside the class. This may be useful to provide a shorter name for the type in the implementation context only.

Another example: private renaming of a type parameter

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

with roughly the same use case.

Making it secure can also make sense. Example:

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 
}
+5

Source: https://habr.com/ru/post/1656504/


All Articles