Kotlin Collections Advice

Coming to Kotlin from Scala, I’m not sure what is the most idiomatic (or any) way of using rich collections. So what I mean is, in Scala I can do this:

val iterator = .. // create an iterator
iterator.drop(3).takeWhile(_.isNonEmpty).toList

My use case is that I have a Java API that reads records in a CSV and offers me the method parseNext which returns an Array<String> or null. In the code snippet above, I would create the iterator by something like:

val iterator = new Iterator[Array[String]] {
  def hasNext = ...
  def next = ...
}

And then I could use that iterator with all the rich methods - drop, take, takeWhile, andThen, etc.

What’s the best way to get this same functionality in Kotlin. The answer might even be - just use Java 8 collections (I moved to Scala well before Java 8 came out so not too familiar with Java 8 streams).

Did you already seen generateSequence - Kotlin Programming Language?

2 Likes

Ah that’s perfect, thanks.

Any ideas for when what you have is a kind of iterator already, eg something like ResultSet, which doesn’t return null, but relies on the user calling hasNext() before calling next().

Never mind, it’s as easy as generateSequence { if (rs.next) rs else null }