I am quite new to Scala and got a few unresolved problems with the following code:
object exprs{
println("Welcome to the Scala worksheet")
def show(e: Expr): String = e match {
case Number(x) => x.toString
case Sum(l, r) => show(l) + " + " + show(r)
}
show(Sum(Number(1), Number(44)))
}
trait Expr {
def isNumber: Boolean
def isSum: Boolean
def numValue: Int
def leftOp: Expr
def rightOp: Expr
def eval: Int = this match {
case Number(n) => n
case Sum(e1, e2) => e1.eval + e2.eval
}
}
class Number(n: Int) extends Expr {
override def isNumber: Boolean = true
override def isSum: Boolean = false
override def numValue: Int = n
override def leftOp: Expr = throw new Error("Number.leftOp")
override def rightOp: Expr = throw new Error("Number.rightOp")
}
class Sum(e1: Expr, e2: Expr) extends Expr {
override def isNumber: Boolean = false
override def isSum: Boolean = true
override def numValue: Int = e1.eval + e2.eval
override def leftOp: Expr = e1
override def rightOp: Expr = e2
}
I get the following errors:
Error: object Number is not a case class, nor does it have an unapply/unapplySeq member
Error: not found: value Sum
How to resolve them? Thanks in advance
In Scala
case classare likeclasswith extra goodies + some other properties.For a normal class,
You can not create its instance like this,
You will have to use
newto create new instance.Now lets say we have
case class,We can create a new instance of B like this,
The reason this works with
case classis becausecase classhave an auto-created companion objects with them, which provides several utilities including anapplyandunapplymethod.So, this usage
val b = B(5, "five")is actuallyval b = B.apply(5, "five"). And hereBis not theclass Bbut the companionobject Bwhich is actually proviedsapplymethod.Similarly Scala pattern matching uses the
unapply(unapplySeqfor SeqLike patterns) methods provided by companion object. And hence normalclassinstances do not work with pattern matching.Lets say you wanted to defined a
classand not acase classfor some specific reason but still want to use them with pattern-matching etc, you can provide its companion object with the required methods by yourselves.Also, as you are new to learning Scala you should read http://danielwestheide.com/scala/neophytes.html which is probably the best resource for any Scala beginner.