The Expression abstract class is created with 4 other case classes.
Write a function which takes an Expresssion object as input, and use match so that when an Expression object is taken:
It is a number is printed for Number object.
It is a string expression is printed for Var object.
It is a unary operation is printed for UnOp object.
It is a binary operation is printed for BinOp object.
Invalid Expression is printed in all other cases.
Copy the following CaseClass program into the file: abstract class Expression
case class Var(name: String) extends Expression
case class Number(num: Double) extends Expression
case class UnOp(operator: String, arg: Expression) extends Expression
case class BinOp(operator: String, left: Expression, right: Expression) extends Expression
object CaseClassMatching extends App {
val op = BinOp("+", Number(1), Number(4))
describe(op)
def describe //write your code here
}
} After copying, press Esc followed by :wq to save the file.
Compile the program using:
scalac CaseClass.scala
Execute the program to print the outputs:
scala CaseClassMatching
Output will be:
It is a binary operation