I have a variable underlying of type Option[mutable.Traversable[Field]]
All I wanted todo in my class was provide a method to return this as Sequence in the following way:
def toSeq: scala.collection.mutable.Seq[Field] = {
for {
f <- underlying.get
} yield f
}
This fails as it complains that mutable.traversable does not conform to mutable.seq. All it is doing is yielding something of type Field - in my mind this should work?
A possible solution to this is:
def toSeq: Seq[Field] = {
underlying match {
case Some(x) => x.toSeq
case None =>
}
}
Although I have no idea what is actually happening when x.toSeq is called and I imagine there is more memory being used here that actually required to accomplish this.
An explanation or suggestion would be much appreciated.
I am confused why you say that "I imagine there is more memory being used here than actually required to accomplish". Scala will not copy your
Fieldvalues when doingx.toSeq, it is simply going to create an newSeqwhich will have pointers to the sameFieldvalues thatunderlyingis pointing to. Since this new structure is exactly what you want there is no avoiding the additional memory associated with the extra pointers (but the amount of additional memory should be small). For a more in-depth discussion see the wiki on persistent data structures.Regarding your possible solution, it could be slightly modified to get the result you're expecting:
This solution will return an empty
Seqifunderlyingis aNonewhich is safer than your original attempt which usesget. I say it's "safer" becausegetthrows aNoSuchElementExceptionif the Option is aNonewhereas mytoSeqcan never fail to return a valid value.Functional Approach
As a side note: when I first started programming in scala I would write many functions of the form:
This is less functional because you are expecting a particular collection type, e.g.
formatSeqwon't work on aFuture.I have found that a better approach is to write:
Or my preferred coding style:
Then the user of your function can apply
formatStrin any fashion they want and you don't have to worry about all of the collection casting: