Joh*_*yns 4 printing scala immutability
目前正在使用一个我以前从未使用过Scala的类,所以语法和本身都是新的.
我正在研究一个简单的除法函数,但遇到了一些错误.
首先,我使用var sub = m对吗?在我的代码中,我只想做m = mn,但你不能改变变量,我不确定最好的选择是什么.然后我唯一的另一个问题是编译器对我的打印线咆哮..
<console>:14: error: reassignment to val
m = m-n
Run Code Online (Sandbox Code Playgroud)
////////////////////////////////////////////////// /////////////////////////////
<console>:16: error: type mismatch;
found : Unit
required: Int
println(x)
Run Code Online (Sandbox Code Playgroud)
////////////////////////////////////////////////// /////////////////////////////
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)
}
Run Code Online (Sandbox Code Playgroud)
问题实际上是你的回报价值.您声明div返回a Int并且编译器(在您的情况下)假定您的最后一个语句是您的返回值.由于println回报率Unit(这是一个void函数),编译器混淆.
您可以通过return x在函数中的任何位置显式返回值,也可以将其x作为函数中的最后一个语句(或该函数中的一个特定执行路径).例如:
def what(b:Boolean):Int = {
if(b) 1
else 0
}
Run Code Online (Sandbox Code Playgroud)
(Scala允许我写def what(b:Boolean) = if(b) 1 else 0,它将与上面的功能完全相同,但除此之外.)
为方便起见,这是您的功能,我所描述的修改:
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
}
Run Code Online (Sandbox Code Playgroud)