如何增加在Scala中传递给函数的整数变量? [英] how do I increment an integer variable I passed into a function in Scala?
本文介绍了如何增加在Scala中传递给函数的整数变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在函数外部声明了一个变量,如下所示:
I declared a variable outside the function like this:
var s: Int = 0
通过了这样的请求:
def function(s: Int): Boolean={
s += 1
return true
}
但是对于我来说,错误行不会消失在"s + ="下.我尝试了一切.我是Scala btw的新手.
but the error lines wont go away under the "s +=" for the life of me. I tried everything. I am new to Scala btw.
推荐答案
首先,我要重申我的警告:以下解决方案既晦涩又效率低,如果可能的话,请坚持下去和val
ues.
First of all, I will repeat my words of caution: solution below is both obscure and inefficient, if it possible try to stick with val
ues.
implicit class MutableInt(var value: Int) {
def inc() = { value+=1 }
}
def function(s: MutableInt): Boolean={
s.inc() // parentheses here to denote that method has side effects
return true
}
这是运行中的代码:
scala> val x: MutableInt = 0
x: MutableInt = MutableInt@44e70ff
scala> function(x)
res0: Boolean = true
scala> x.value
res1: Int = 1
这篇关于如何增加在Scala中传递给函数的整数变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文