【问题标题】:Is there a way to avoid using var in this scala snippet有没有办法避免在这个 scala 片段中使用 var
【发布时间】:2021-10-15 21:07:50
【问题描述】:

下面是代码 sn-p,我想避免使用 'var'。不知道有没有什么好的方法

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

【问题讨论】:

  • 您能否提供更多背景信息:这将如何使用?
  • 简答,不。根据定义,您的设计是可变的。
  • @GaëlJ 我只需要一个进程的随机数生成器,我可能想在给定场景中检索先前生成的数字,而在另一个场景中,我想要一个新数字。

标签: scala


【解决方案1】:

创建一个“无限的”Iterator 随机数。仅在需要时才转至next()

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

  randomInt.head
}

【讨论】:

  • 我很困惑。它买什么? var 的代码似乎更清晰。
【解决方案2】:

下面的类保存了当前的随机值,并提供了一个方法来返回一个保存下一个随机值的实例。

它只使用不可变的值,尽管 Random.nextInt(...) 函数不是纯函数,因为它不会为相同的输入返回相同的结果。

该课程是您的 3 个要求的直接翻译:

  1. 检索之前生成的号码。
  2. 生成新号码。
  3. 避免使用“var”。

这显示了返回新的不可变实例而不是改变变量的基本技术,尽管我发现jwvhinfinite iterator answer 是一个更优雅的解决方案。

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()
    })
  }
}

【讨论】:

    【解决方案3】:

    不确定你也打开了哪些更改,你可以简单地添加一个参数

    val randomInt = Random.nextInt(100)
    private def getRandomInt(createNew:Boolean,previous:Int):Int = {
      if(createNew) Random.nextInt(100) else previous
    }
    

    【讨论】:

    • 不要认为它会有用,因为在首先调用这个方法之前我们没有关于前一个的信息。我错过了什么吗?
    • 不确定你的意思,你有一个 randomInt var,你只需将它传入 getRandomInt(true,randomInt)
    • 问题是在您使用 'true' 参数作为 getRandomInt(true,randomInt) 调用函数之后,我想使用 'false' 参数调用它,但调用者没有信息关于'previous',这是第二个参数,因为它是从第一个参数以外的其他地方调用的,因此它不太有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2015-03-05
    • 2010-09-24
    • 2019-09-07
    • 1970-01-01
    相关资源
    最近更新 更多