1

In Java, the abstract class's static member will be inherited all through its subclasses. like

abstract class TopThing{
  public TopThing next;
  public TopThing(TopThing tt){
        this.next = tt
  }

  private static HashTable<String, TopThing> someTable = new HashTable<String,TopThing>();
  protected void add(String name) {
      someTable.put(name, this);
  public static Parent forName(String name) {
      return someTable.get(name)    ;
  }
}

class SomeSpecific extends TopThing {
    public final String name;
    public SomeSpecific (String name, TopThing tt) {
       super(tt);
       this.name = name;
       this.add(name);
}

This is I am first time writing in Scala, the only way I know to achieve the above is using companion object, but it seems does not work for this case

  • Can companion object store the private static table? (it seems no...)
  • If I can declare the table in the companion object, can it be referenced from companion class? ( it seems no...)
  • In the add method, how can the subclass's instance referred and be inserted into the table? (the question is also about this in add method)
  • What's a good practice of this in Scala?

2 Answers 2

6
  1. Yes, it can.

  2. Yes, you reference it as TopThing.someTable (or just someTable after import TopThing._).

  3. Same as in Java: this. So

    abstract class TopThing(val next: TopThing) {
      protected def add(name: String) {
        TopThing.someTable += (name -> this)
      }
    }
    
    object TopThing {
      private val someTable = collection.mutable.Map[String,TopThing]()
    
      def forName(name: String) = someTable.get(name)
    }
    
    class SomeSpecific(val name: String, next: TopThing) extends TopThing(next) {
      this.add(name)
    }
    
Sign up to request clarification or add additional context in comments.

Comments

0

For question 1: you can use private[namespace]

For question 2: no, but you can use import

class Xxx {
  import Xxx._
  ...
}  

For question 3: I don't known how to answer it.

For question 4:

trait TopThing {
  val someTable: HashTable[String, TopThing] 
}
class Xxx extend TopThing {
  val someTable = Xxx.someTable  
}

2 Comments

"I don't known how to answer it." I'd love to have this on a quality t-shirt. Preferably with a lolcat. Also, I would +1 for answering bullet #4, except that someTable should be theTable, I think, as in the other response.
Putting the table in a trait will create one per instance which is not at all the same thing as the Java code's static table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.