score:7

Accepted answer

Remove the abstract keyword and turn the class Expr into object Expr. As far as your code goes I see no reason to don't make these changes.

But, if you indeed want to keep you Expr an abstract class you will have to extend and instantiate it:

def main(args:Array[String]) {
    val expr = new Expr {} // extending the class - this creates a anonymous class
    val v = expr.Var("x")

    // alternatively, since now we do have a object to import
    import expr._
    val v2 = Var("x")

    // even another approach, now using a named class
    class MyExpr extends Expr
    val myexpr = new MyExpr
    val v3 = myexpr.Var("x")
}

Explanations:

  • Only objects and packages can have its members imported
  • Abstract classes have to be extended in order to be instantiated. The idea here is that some "point(s)" in class will is required to be defined by the client while still sharing the rest of interface with other extensions of the abstract class.

Related Query

More Query from same tag