I have a Scala class with two parameters, and another one parameter constructor. For the one parameter constructor, I called a method to get a tuple of two elements and tried to use the tuple for the parameter of the constructor that requires two parameters. From this post: Scala tuple unpacking for constructors I could get an answer for the non-inheritance case, but I need to use the method for inheritance case.
This is my code, but I'm not sure how to instantiate the abstract class.
abstract class A(val a:Int, val b:Int) {
def h()// = ???
}
object A {
def apply(pair: (Int, Int)): A = new A(pair._1, pair._2)
def apply(v: Int): A = A(vals(v))
def vals(v:Int) = {
(v,v)
}
}
class B(override val a:Int, override val b:Int) extends A(a,b) {
override def h() = ???
}
object B {
def apply(pair: (Int, Int)): B = new B(pair._1, pair._2)
def apply(v: Int): B = B(A.vals(v))
}
object Main extends App {
val a = B(10)
println(a.a, a.b)
}
Of course, I got an error message if I tried to instantiate the abstract class.
error: class A is abstract; cannot be instantiated
def apply(pair: (Int, Int)): A = new A(pair._1, pair._2)
^
I think the simplest solution is just make the abstract class non abstract, and giving dummy body def h() = ???
. However, I'm not sure there might be better way.