How do I increment an integer variable that I passed to a function in Scala?

I declared a variable outside a function like this:

var s: Int = 0

passed it like this:

def function(s: Int): Boolean={

   s += 1

   return true

}

but the error lines will not disappear under "s + =" for the life of me. I tried everything. I am new to Scala btw.

+5
source share
5 answers

First of all, I will repeat my warnings: the solution below is unclear and ineffective , if possible, try to stick to 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 the code in action:

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

scala> function(x)
res0: Boolean = true

scala> x.value
res1: Int = 1
+3
source

If you just want to continuously increment integers, you can use Stream.

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

This creates an iterator over an infinite stream of numbers, starting from zero. Then, to get the next number, call

val number: Int = numberStream.next
+2

Scala, .

var s: Int = 0

def function(s: Int): Boolean={

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

}

, , "s" , . , , .

+1

.

A var - , , . , , .

, , , , . , . , .

. , , .

0

, 3

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

:

NextID ()

-1
source

All Articles