问题描述
当前正在使用一个我从未使用过的使用Scala的类,因此语法及其本身是新的.
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.
首先,我使用的是var sub = m吗?在我的代码中,我只是想做m = m-n,但是您不能更改变量,而且我不确定最好的选择是什么.然后,我唯一的另一个问题是编译器在我的打印行中咆哮着.
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)
}
推荐答案
问题实际上是您的返回值.您声明了div
返回一个Int
,并且编译器(在您的情况下)假定您的最后一条语句为返回值.由于println
返回Unit
(这是一个void
函数),因此编译器感到困惑.
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.
您可以通过在函数中的任何位置说出return x
来显式地返回一个值,或者可以将x
作为函数中的最后一条语句(或该函数中的一条特定执行路径).例如:
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允许我编写def what(b:Boolean) = 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
}
这篇关于Scala不可变变量和打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!