John Redyns
John Redyns

Reputation: 5903

Scala immutable variables and printing

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)
}

Upvotes: 4

Views: 951

Answers (2)

Jed Wesley-Smith
Jed Wesley-Smith

Reputation: 4706

For completeness, putting more idiomatic recursive definition here:

def div(m: Int, n: Int): Int = {
  @annotation.tailrec
  def loop(count: Int, sub: Int): Int = 
    if (sub < n) count
    else loop(count + 1, sub - n)

  loop(0, m)
}

Upvotes: 3

Dylan
Dylan

Reputation: 13859

The problem is actually your return value. You declared div to return an Int and the compiler (in your case) is assuming your last statement to be your return value. Since println returns Unit (it's a void function), the compiler is confused.

You can explicitly return a value by saying return x anywhere in your function, or you can put x as the last statement in the function (or one particular path of execution in that function). For example:

def what(b:Boolean):Int = {
  if(b) 1
  else 0
}

(Scala would allow me to write def what(b:Boolean) = if(b) 1 else 0 and 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:

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)
  x // <--- return value
}

Upvotes: 7

Related Questions