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.")
   {
   }
0

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

This works, but my situation is very simple so the other answer works just fine. Thanks though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.