Reputation: 53806
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
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:
Upvotes: 7