Currently taking a class that’s using Scala which I’ve never used before, so the syntax and itself is new.
I’m working on a simple division function but am running into some errors.
First of all, am I using var sub=m right? In my code I simply wanted to do m = m-n but you can’t change the variable, and I’m not sure what the best alternative is.
Then my only other problem is the compiler barks at me for my print line..
<console>:14: error: reassignment to val
m = m-n
///////////////////////////////////////////////////////////////////////////////
<console>:16: error: type mismatch;
found : Unit
required: Int
println(x)
///////////////////////////////////////////////////////////////////////////////
def div(m: Int, n: Int): Int = {
var x = 0
var sub = m
if (n > m)
print("Can't perform that.")
while (sub >= n) {
x+=1
sub = sub-n
}
println(x)
}
The problem is actually your return value. You declared
divto return anIntand the compiler (in your case) is assuming your last statement to be your return value. SinceprintlnreturnsUnit(it’s avoidfunction), the compiler is confused.You can explicitly return a value by saying
return xanywhere in your function, or you can putxas the last statement in the function (or one particular path of execution in that function). For example:(Scala would allow me to write
def what(b:Boolean) = if(b) 1 else 0and it would be exactly the same function as above, but that is besides the point.)For convenience, here is your function with the modification I described: