0

I wanted to add different objects to an ArrayBuffer collection, so I have to define a base class

case class base (a:String,b:String)
case class Super1 (a:String, b:String, c:String) extends base(a,b)
case class Super2 (a:String, b:String, c:String, d:String) extends base(a,b)
val array=New ArrayBuffer[base]()
val super1=new Super1("1","2","super1")
val super2=new Super2("1","2","super2","super2")
array+=(super1)
array+=(super2)

Actually, have not tested the above code but want to know if the adding object are Super1 or Super2 instead of the base class as I need the value of all parameters in the derived classes..

1 Answer 1

1

Your first problem is that you can't inherit from a case class. Use a straight class or trait and you're OK.

After the class instances have been loaded into, and then extracted from, the ArrayBuffer, you can use pattern matching to determine the correct type.

array+=super1
array+=super2
array.head match {
  case Super1(a,b,c) => println("got 1")
  case Super2(a,b,c,d) => println("got 2")
  case _ => println("got bad")
}

There are a few other problems with your "not tested" code, but they're easily addressed.

2
  • Hi, If I add a trait to base class such as extends Ordered [base] { def compare (that: base) = { if (this.length == that.length) 0 else if (this.length> that.length) 1 else −1 }}..do I need to implement them on child classes?
    – Mahdi
    Sep 8, 2016 at 4:22
  • @user2021147; 1st -- It's not proper to ask a new question in the comments section of a previous question because A) fewer people will see it and offer answers, and B) whoever answers the new question can't get any up-votes and reputation points. 2nd -- This question is easily answered just by dropping a few lines of code into a REPL or IDE. 3rd -- No. After the base is Ordered then all the child classes are as well. No override is needed unless you want to change the Ordered rules.
    – jwvh
    Sep 8, 2016 at 4:49

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.