Reputation: 1523
I have the following function in 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
}
Its being called as
path.map(x => pathToBeRedacted(x, 2)).flatten
How can I get rid of the var and still add it values to the sequence ?
Upvotes: 0
Views: 60
Reputation: 44918
It seems that you are returning an at-most-one-element Seq
,
so you might as well do this:
def pathToBeRedacted(p: Path, redactProperty: Int): Seq[Vertex] = {
createVertexFromPath(p.objects(), redactProperty).toSeq
}
This works because Option
is implicitly convertible to Iterable
, and Iterable
has a toSeq
.
If you want to keep the solution closer to your code and only eliminate the var, then you can return the result of match
directly:
def pathToBeRedacted(p: Path, redactProperty: Int): Seq[Vertex] = {
val seq = Seq.empty[Vertex]
val l = p.objects()
val r = createVertexFromPath(l, redactProperty)
r match {
case Some(x) => seq :+ x
case None => seq
}
}
Upvotes: 4