Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 767
J L Avatar asked Mar 29 '13 14:03

J L


2 Answers

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
like image 86
om-nom-nom Avatar answered Sep 21 '22 22:09

om-nom-nom


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
like image 24
Ron Romero Avatar answered Sep 19 '22 22:09

Ron Romero