Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I access private class methods in the class's companion object in Scala?

I'm working on a homework assignment for my object oriented design class, and I'm running into trouble with Scala's companion objects. I've read in a few places that companion objects are supposed to have access to their companion class's private methods, but I can't seem to get it to work. (Just as a note, the meat of the assignment had to do with implementing a binary search tree, so I'm not just asking for answers...)

I have an object that is supposed to create an instance of my private class, BstAtlas (Bst is also defined in the Atlas object, took 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's methods
    ...
  }
}

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

Question23.scala:15: error: method helpFocusRoom cannot be accessed in Atlas.Atlas a.helpFocusRoom(newRoom);

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

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

like image 560
Shaun Avatar asked Oct 28 '10 18:10

Shaun


People also ask

Can private method be accessed by object?

Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.

Which operations are provided by collection companion object in Scala?

A companion object and its class can access each other's private members. A companion object's apply method lets you create new instances of a class without using the new keyword. A companion object's unapply method lets you de-construct an instance of a class into its individual components.

What is the advantage of companion object in Scala?

Advantages of Companion Objects in Scala Companion objects provide a clear separation between static and non-static methods in a class because everything that is located inside a companion object is not a part of the class's runtime objects but is available from a static context and vice versa.


1 Answers

The problem is that classes and companion objects can't be nested like that. To define a companion object, you need to define the class outside of the object's body but in the same file.

like image 141
Dave Griffith Avatar answered Sep 27 '22 21:09

Dave Griffith