david hol david hol - 2 months ago 6
Scala Question

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
?

Answer

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)
Comments