Calling the case class from the main method inside the object

In this class below:

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 follows:

 package patternmatching import patternmatching.Expr.Var object PatternMain { def main(args:Array[String]) { val v = Var("x") } } 

But I get a compile-time error in PatternMain in the line import patternmatching.Expr.Var :

  • The Expr object is not a member of the patternmatching package Note: The Expr class exists, but it does not have a companion object.

How to correctly call val v = Var("x") for the case Var class? I do not import it correctly?

+4
source share
1 answer

Remove the abstract keyword and turn class Expr into object Expr . As for your code, I see no reason not to make these changes.

But if you really want your Expr abstract class you have to extend and create 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 import their items.
  • Abstract classes must be extended to be instantiated. The idea here is that some β€œpoints (s)” in the class will be necessary for the client to define, while at the same time sharing the rest of the interface with other extensions of the abstract class.
+7
source

Source: https://habr.com/ru/post/1440413/


All Articles