【问题标题】:Best way to build and return a list from a method从方法构建和返回列表的最佳方法
【发布时间】:2013-06-11 13:34:30
【问题描述】:

是否有一个 Scala 构造来构建和返回这样的列表?

def getOutput(isValidInput: Boolean): List[Output] =
  if (isValidInput) {
    yield Output(1) // Pseudo-code... I know yield is not intended for this!
    yield Output(2)
  }

而不是...

def getOutput(isValidInput: Boolean): List[Output] =
  if (isValidInput)
    List(Output(1), Output(2))
  else
    Nil

在 C# 中,“yield”的使用允许您返回惰性求值的集合 - 在 Scala 中是否有类似的东西?

【问题讨论】:

  • 如果你想要代码的懒惰或简洁,我不清楚这个问题。除非布尔值为真,否则不会在您的示例中创建列表。
  • 你想要的是一种延续形式。这有点受支持,但可能比其他选项可读性差。见scala-lang.org/node/2096

标签: scala scala-2.10


【解决方案1】:

如果您想要一个惰性序列,请使用 Stream:

case class Output(value: Int)

def getOutput(isValidInput: Boolean):Stream[Output] = getOutput(isValidInput, 1)

def getOutput(isValidInput: Boolean, index: Int):Stream[Output] =
  if (isValidInput && index < 3) {
    println("Index: " + index)
    Output(index) #:: getOutput(isValidInput, index+1)
  } else {
    Stream.empty[Output]
  }

println("Calling getOutput")
val result: Stream[Output] = getOutput(true)
println("Finished getOutput")

result foreach println

这会导致:

Calling getOutput
Index: 1
Finished getOutput
Output(1)
Index: 2
Output(2)

如果您想保持返回类型为List[Output],使用yield 是一种有效的方法:

def getOutput(isValidInput: Boolean):List[Output] =
  if (isValidInput) {
    (for (i <- 1 until 3) yield Output(i))(collection.breakOut)
  } else {
    List.empty[Output]
  }

另外,使用Vector 通常比List 更可取。

相关:

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 2021-12-18
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多