Home > Blockchain >  Is there a way to avoid using var in this scala snippet
Is there a way to avoid using var in this scala snippet

Time:10-15

Below here the code snippet, where I want to avoid using the 'var'. Not sure if there is a good way to do that

var randomInt = Random.nextInt(100)
private def getRandomInt(createNew:Boolean):Int = {
  if(createNew){
    randomInt = Random.nextInt(100)
  }
  randomInt
}

CodePudding user response:

Create an "infinite" Iterator of random numbers. Advance to the next() only when needed.

val randomInt = Iterator.continually(Random.nextInt(100)).buffered
private def getRandomInt(createNew:Boolean):Int = {
  if (createNew) randomInt.next()

  randomInt.head
}

CodePudding user response:

The class below holds the current random value and provides a method to return an instance holding the next random value.

It only uses immutable values, although the Random.nextInt(...) function isn't pure, because it doesn't return the same result for the same input.

The class is a direct translation of your 3 requirements:

  1. to retrieve the previously generated number.
  2. to generate a new number.
  3. avoid using the 'var'.

This shows the basic technique of returning a new immutable instance instead of mutating a variable, although I find the infinite iterator answer by jwvh to be a more elegant solution.

import scala.util.Random

// A random number generator that remembers its current value.
case class RandomInt(size: Int) {
  val value = Random.nextInt(size)

  def nextRandomInt(): RandomInt = RandomInt(size)
}

// Test case
object RandomInt {
  def main(args: Array[String]): Unit = {
    val r0 = RandomInt(100)

    (0 to 99).foldLeft(r0)((r, i) => {
      println(s"[$i] ${r.value}")
      r.nextRandomInt()
    })
  }
}
  • Related