简体   繁体   中英

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 = mn 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 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
}

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM