david hol
david hol

Reputation: 1280

How to define count without using var

I have this simple function that return some Status:

def getStatus : String =
{
   //...
}

And i want to wait until this return specific status but still count this number of calls before exit:

def wait =
{
    var count = 0
    while (getStatus != "smeStatus" && count < 10) {

        // some code here
        count++
    }
}

How can i avoid of using var ?

Upvotes: 2

Views: 724

Answers (2)

jacks
jacks

Reputation: 4783

  def status = ""

  def waiting: Unit = {
    def check(count: Int): Unit = {
      if(count < 10 && status != "smeStatus") {
        // do something
        check(count + 1)
      } 
    }
    check(0)
  }

Upvotes: 0

Tzach Zohar
Tzach Zohar

Reputation: 37852

You can use a recursive method that takes the count-so-far and returns it + 1:

def waitUntilDone(countSoFar: Int): Int = {
  if (getStatus != "smeStatus" && countSoFar < 10) {
    // some code here
    waitUntilDone(countSoFar + 1)
  } else {
    countSoFar
  }
}
// invoke it starting with 0:
val count = waitUntilDone(0)

Upvotes: 3

Related Questions