0

So I have this variable, currentPartNumber, which starts off being equal to 0. What I want to happen is in my function, if the variable is equal to zero, it is changed to 1 and the text is printed out. Same thing for my second function - if the variable was changed to 1 in my first function and is equal to one, I want the variable to change to 2 an print out the text.

The problem is: How do I get the variable to change with each function call like I want?

var currentPartNumber = 0

def roomOne():Unit = {
   if (currentPartNumber < 1) {
      var currentPartNumber = 1
      println("You now have parts 1 of 4.")
     } else {
      println("This part cannot be collected yet.")
   {
   }


def roomTwo():Unit = {
   if (currentPartNumber = 1) {
      var currentPartNumber = 2
      println("You now have parts 2 of 4.")
     } else {
      println("This part cannot be collected yet.")
   {
   }
Chris
  • 233
  • 2
  • 5
  • 14

2 Answers2

3

Don't shadow the variable: remove the var from inside the functions.

The var keyword declares a new member/variable. In this case the name is the same which shadows the variable from the outer scope. Thus the assignment (as part of the declaration) has no affect on the outer variable.

// no var/val - assignment without declaration
currentPartNumber = 2

See also:

Community
  • 1
  • 1
1

Declare currentPartNumber in a class where roomOne() and roomTwo() can access and modify it.

class Parts{
  var currentPartNumber = 0

  def roomOne():Unit = {
    if (currentPartNumber < 1) {
      currentPartNumber = 1
      println("You now have parts 1 of 4.")
    } else {
      println("This part cannot be collected yet.")
    } 
  }  

  def roomTwo():Unit = {
    if (currentPartNumber == 1) {
       currentPartNumber = 2
       println("You now have parts 2 of 4.")
     } else {
      println("This part cannot be collected yet.")
     }
   }
}



scala> :load Parts.scala
Loading Parts.scala...
defined class Parts
scala> var parts = new Parts
parts: Parts = Parts@5636a67c
scala> parts.currentPartNumber
res0: Int = 0
scala> parts.roomOne
You now have parts 1 of 4.
scala> parts.roomTwo
You now have parts 2 of 4.
Brian
  • 20,195
  • 6
  • 34
  • 55
  • This works, but my situation is very simple so the other answer works just fine. Thanks though! – Chris Mar 28 '13 at 04:56