1

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.

Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871
  • 2
    Since an `A` can never be instantiated directly, there is no need here for constructors or factory methods for it - drop the companion object for `A` (and move the `vals` method over to `B`'s companion object) and you should be fine. – Shadowlands Sep 10 '15 at 23:35
  • @Shadowlands: I got it thanks. – prosseek Sep 10 '15 at 23:52

1 Answers1

0

From Shadowlands' hint, I could just use the apply() only for concrete classes.

// http://stackoverflow.com/questions/32512401/scala-tuple-unpacking-for-constructors


abstract class A(val a:Int, val b:Int) {
    def h()// = ???
}

object A {
    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)
}
prosseek
  • 182,215
  • 215
  • 566
  • 871