monica
monica

Reputation: 1065

How to implement this Java mechanism in Scala?

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

Upvotes: 1

Views: 125

Answers (2)

Tim Green
Tim Green

Reputation: 3649

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  
}

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170859

  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)
    }
    

Upvotes: 6

Related Questions