Kotlin Collections Advice


#1

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).


#2

Did you already seen http://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/generate-sequence.html?


#3

Ah that’s perfect, thanks.


#4

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().


#5

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