从函数中删除var

时间:2018-03-07 19:13:39

标签: scala

我在scala中有以下功能

def pathToBeRedacted(p: Path, redactProperty: Int): Seq[Vertex] = {

    var seq = Seq.empty[Vertex]
    val l = p.objects()

    val r = createVertexFromPath(l, redactProperty)
    r match {
      case Some(x) => seq :+= x
      case None =>
    }
    seq

  }

被称为

path.map(x => pathToBeRedacted(x, 2)).flatten

如何摆脱var并仍然将其添加到序列中?

1 个答案:

答案 0 :(得分:4)

您似乎正在返回最多一个元素Follow.aggregate([ { $match: { "id": "2" } }, { $lookup:{ from:"users", localField:"follow id", foreignField:"id", as:"fromItems" } }, { $project: { id: "$follow id", from: { $arrayElemAt: ["$fromItems", 0 ] } } }, { $project : { id : 1, name: "$from.name", age: "$from.age" } } ]) , 所以你不妨这样做:

Seq

这是有效的,因为def pathToBeRedacted(p: Path, redactProperty: Int): Seq[Vertex] = { createVertexFromPath(p.objects(), redactProperty).toSeq } 可以隐式转换为OptionIterableIterable

如果您希望让解决方案更接近您的代码并且只消除var,那么您可以直接返回toSeq的结果:

match