tags:

views:

89

answers:

1

ArrayBuffer extends ResizableArray which include a protected method, swap. Yet I can't access swap. What am I missing?

scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> val x=new ArrayBuffer[Int]() 
x: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> x+=3

scala> x+=5

scala> x.swap(0,1)
<console>:7: error: method swap cannot be accessed in scala.collection.mutable.ArrayBuffer[Int]
       x.swap(0,1)
         ^
+3  A: 

According to this documentation, swap is declared as a protected method - which means that while you could access it within the code of ArrayBuffer (or any other class derived from ResizableArray), you can't access it from other class.

From the Scala Language Specification, page 57:

The protected modifier applies to class member definitions. Protected members of a class can be accessed from within
– the template of the defining class,
– all templates that have the defining class as a base class,
– the companion module of any of those classes.

You're not in any of those contexts, which is why you're seeing an error.

Jon Skeet
Yes, protected means that the subclass, ArrayBuffer, could call the protected superclass function swap(). It does not mean that instances of the subclass create public access to protected superclass methods.
DrGary