Chris
Chris

Reputation: 233

How do I get this Scala count down function to work?

Basically what I want this code to do is define a function, timeCount, and each time it is called I want 1 to be subtracted from 21, have the result be printed out, and have the result equal timeNum. So, I want 1 to be subtracted from 21, resulting in 20, printing out 20, then making timeNum equal to 20. Then the next time the function is called, it would be equal to 19, 18, etc, etc, ...

However, this code does not work. How can I get what I want to happen?

def timeCount() = {
  var timeNum = 21
  var timeLeft = timeNum-1
  println(timeLeft)
  var timeNum = timeLeft
 }
}

Upvotes: 1

Views: 769

Answers (2)

stew
stew

Reputation: 11366

class TimeCount(initial: Int) extends Function0[Int] {
  var count = initial

 def apply = {
    count = count - 1
    count
 }
}

Use it like this:

scala> val f = new TimeCount(21)
f: TimeCount = <function0>

scala> f()
res0: Int = 20

scala> f()
res1: Int = 19

scala> f()
res2: Int = 18

I made two changes from what you were asking for, I made the number to start with a parameter to the constructor of the function, and I returned the count instead of printing it, because these seem more useful If you really just want to print it, change Function0[Int] to Function0[Unit] and change count to println(count.toString)

This is, of course, not threadsafe.

Upvotes: 2

Dave Swartz
Dave Swartz

Reputation: 910

As the compiler error below states, you defined the same var twice.

console>:11: error: timeNum is already defined as variable timeNum
         var timeNum = timeLeft
             ^

Keep in mind, one can modify the value of a var, but not to define it again.

Additionally, you declare and initialize the timeNum var in the function call. The result being that once it does compile you will print the same value (20) repeatedly.

Also, the timeLeft var is superfluous.

Upvotes: 1

Related Questions