I am fairly new to scala and I am doing my assignment. This is the code that I am using:
case EqNumC(l,r) => (interp(l),interp(r)) match{
case (NumV(s),NumV(x)) => if(s == x) BoolV(true) else BoolV(false)
case _ => throw InterpException("Value not found!")
}
When I run this code, it works fine and I get my result correctly. However this is somehow wrong. and I decided to make it better, by doing so:
case EqNumC(l,r) => (interp(l),interp(r)) match{
case (NumV(s),NumV(x)) => if(s==x) BoolV(true)
case (NumV(_),NumV(_)) => BoolV(false)
case _ => throw InterpException("Value not found!")
}
However When I run this I get this error:
Status: CompilationFailure
solution.scala:129: error: type mismatch;
found : Unit
required: Value
case (NumV(s),NumV(x)) => if(s==x) BoolV(true)
^
I don't see the problem here, because it's almost the same as the other one. How can I get rid of this problem and what is the best way to get this done?
The if
control structure needs to come before the =>
when pattern-matching. When it comes after, the compiler sees an if
without an else
and infers it to be Unit
(no return type).
It should look like this:
case (NumV(s),NumV(x)) if(s == x) => BoolV(true)
The first version works because if/else
returns a value, but a single if
does not.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.