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

后端 未结 5 1412
深忆病人
深忆病人 2021-01-18 05:34

I declared a variable outside the function like this:

var s: Int = 0

passed it such as this:

def function(s: Int):         


        
5条回答
  •  北海茫月
    2021-01-18 06:09

    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
    

提交回复
热议问题