tags:

views:

151

answers:

3

How do you make a protected method in a class accessible to just all classes in the package in Scala?

+8  A: 

Turns out you can do

protected[packagename] def fn() {...}
Jija
Yes, but lets call that what it is: a method. Functions in Scala are something else entirely.
Randall Schulz
+2  A: 

If we pay attention to the distinction between function and method, we can define an object deriving from Function:

protected[packagename] object fn extends (Int=>Int) {
  def apply(n: Int) = 2*n 
}

Edit: OK, after the original poster changed his question from function to method, this is no longer relevant.

mkneissl
+1 still because, though no longer relevant, it's still very interesting.
Daniel
+6  A: 

Jija, you already know that the protected keyword has a different meaning in Scala compared to Java, but some readers might not know this. Soooo, let's say we have a class A with a method foo().

  • In Java the protected keyword on foo() grants visibility to all classes in the same package as A and to all classes that inherits from A.

  • In Scala the protected keyword on foo() grants visibility to all classes that inherits from A.

Apparently Jija needs the Java behavior, but it is very seldom I do. Before Scala I often complained (while programming Java) that "I want this method to be private, but I still want subclasses to see it. Why is this not possible?" I regard the changed behavior of protected to be a correction of a design flaw in Java.

Hope you learn to love the Scala way :-)

olle kullberg