Scala immutable variables and printing

后端 未结 2 1263
予麋鹿
予麋鹿 2021-01-19 23:01

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 runnin

相关标签:
2条回答
  • 2021-01-19 23:57

    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)
    }
    
    0 讨论(0)
  • 2021-01-19 23:58

    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
    }
    
    0 讨论(0)
提交回复
热议问题