I'm interoperating with some Java code that uses iterator-like functionality, and presumes you will continue to test it's .next for null values. I want to put it into immutable Scala data structures to reason about it with functional programming.
Right now, I'm filling mutable data structures and then converting them to immutable data structures. I know there's a more functional way to do this.
How can I refactor the code below to populate the immutable data structures without using intermediate mutable collections?
Thanks
{
val sentences = MutableList[Seq[Token]]()
while(this.next() != null){
val sentence = MutableList[Token]()
var token = this.next()
while(token.next != null){
sentence += token
token = token.next
}
sentences += sentence.to[Seq]
}
sentences.to[Seq]
}
You might try to use the
Iterator.iteratemethod in order to simulate a real iterator, and then use standard collection methods liketakeWhileandtoSeq. I'm not totally clear on the type ofthisandnext, but something along these lines might work:You can also extend
Iterableby defining your ownnextandhasNextmethod in order to use these standard methods more easily. You might even define an implicit or explicit conversion from these Java types to this newIterabletype – this is the same pattern you see inJavaConversionsandJavaConverters