blue-sky
blue-sky

Reputation: 53806

Invoke a case class from a main method within an object

In this below class :

package patternmatching

abstract class Expr {

  case class Var(name: String) extends Expr
  case class Number(num: Double) extends Expr
  case class UnOp(operator: String, arg:Expr) extends Expr
  case class BinOp(operator: String, left: Expr, right: Expr) extends Expr


}

I define the main class as :

package patternmatching
import patternmatching.Expr.Var

object PatternMain {

      def main(args:Array[String]) {

         val v = Var("x")
    }

}

But I receive a compile time error in PatternMain at line import patternmatching.Expr.Var :

  • object Expr is not a member of package patternmatching Note: class Expr exists, but it has no companion object.

How do I correctly invoke val v = Var("x") against the case class Var ? Am I not importing it correctly ?

Upvotes: 4

Views: 4106

Answers (1)

pedrofurla
pedrofurla

Reputation: 12783

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.

Upvotes: 7

Related Questions