how do I increment an integer variable I passed into a function in Scala?

醉酒当歌 提交于 2019-12-19 18:52:26

问题


I declared a variable outside the function like this:

var s: Int = 0

passed it such as this:

def function(s: Int): Boolean={

   s += 1

   return true

}

but the error lines wont go away under the "s +=" for the life of me. I tried everything. I am new to Scala btw.


回答1:


First of all, I will repeat my words of caution: solution below is both obscure and inefficient, if it possible try to stick with values.

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
}

And here is code in action:

scala> val x: MutableInt = 0 
x: MutableInt = MutableInt@44e70ff

scala> function(x)
res0: Boolean = true

scala> x.value
res1: Int = 1



回答2:


If you just want continuously increasing integers, you can use a Stream.

val numberStream = Stream.iterate(0)(_ + 1).iterator

That creates an iterator over a never-ending stream of number, starting at zero. Then, to get the next number, call

val number: Int = numberStream.next



回答3:


I have also just started using Scala this was my work around.

var s: Int = 0

def function(s: Int): Boolean={

   var newS = s
   newS = newS + 1 
   s = newS
   return true

}

From What i read you are not passing the same "s" into your function as is in the rest of the code. I am sure there is a even better way but this is working for me.




回答4:


You don't.

A var is a name that refers to a reference which might be changed. When you call a function, you pass the reference itself, and a new name gets bound to it.

So, to change what reference the name points to, you need a reference to whatever contains the name. If it is an object, that's easy enough. If it is a local variable, then it is not possible.

See also call by reference, though I don't think this question is a true duplicate.




回答5:


If you just want to increment a variable starting with 3

val nextId = { var i = 3; () => { i += 1; i } }

then invoke it:

nextId()



来源:https://stackoverflow.com/questions/15705585/how-do-i-increment-an-integer-variable-i-passed-into-a-function-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!