Why can't I access private class methods in a companion class in Scala?

I'm working on homework for my object-oriented design class, and I'm having problems with Scala companion objects. I read in several places that companion objects should have access to their own class methods of a companion class, but I can't get it to work. (As a note, the meat of the assignment was related to the implementation of the binary search tree, so I'm not just asking for answers ...)

I have an object that should instantiate my private class, BstAtlas (Bst is also defined in the Atlas object, pulled it out for clarity):

object Atlas { def focusRoom(newRoom:Room,a:Atlas):Atlas = a.helpFocusRoom(newRoom); abstract class Atlas { ... protected def helpFocusRoom(n:Room):Atlas; ... } private class BstAtlas(bst:Bst) extends Atlas { ... protected def helpFocusRoom(newRoom:Room):Atlas = ... // uses some of bst methods ... } } 

But when I go to compilation, I get the following error:

Question23.scala: 15: error: helpFocusRoom method is not available in Atlas.Atlas a.helpFocusRoom (newRoom);

The helpFocusRoom function must be hidden, but I don’t know how to hide it and still have access to it inside the companion object.

Can someone tell me what I'm doing wrong here?

+6
oop scala
source share
2 answers

The problem is that companion classes and objects cannot be nested this way. To define a companion object, you need to define a class outside the body of the object, but in the same file.

+9
source share

Companion objects should be next to their real object that does not contain it:

 object Example { class C(val i: Int = C.DefaultI) { } object C { protected val DefaultI = 5 } } scala> (new Example.C).i res0: Int = 5 scala> Example.C.DefaultI <console>:11: error: value DefaultI cannot be accessed in object Example.C Example.C.DefaultI 

Alternatively, you can change the scope of the protected keyword to include an object:

 object Example { def value = (new D).hidden class D(val i: Int = 5) { protected[Example] def hidden = i*i } } scala> Example.value res1: Int = 25 

but here you should not call the external object the same as the internal class, or you will have problems referencing it from within the class.

+5
source share

All Articles