Skip to content

Instantly share code, notes, and snippets.

@tateisu
Created December 5, 2020 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tateisu/bc86965340e238c73f3f9adefc89d2e3 to your computer and use it in GitHub Desktop.
Save tateisu/bc86965340e238c73f3f9adefc89d2e3 to your computer and use it in GitHub Desktop.
mapNotNullToIterable
// variations of filterNotNull that returns Iterable.
// it proxies iteration to avoid cost of create/update a list.
fun <T> Iterable<T?>.filterNotNullToIterable() =
object : Iterable<T> {
override fun iterator() = object : Iterator<T> {
val source = this@filterNotNullToIterable.iterator()
var item: T? = null
private fun read() {
while (source.hasNext()) {
item = source.next() ?: continue
return
}
item = null
}
init {
read()
}
override fun hasNext(): Boolean = item != null
override fun next(): T = item!!.also { read() }
}
}
// variations of map() that returns Iterable.
// it proxies iteration to avoid cost of create/update a list.
fun <I : Any?, T : Any?> Iterable<I>.mapToIterable(transform: (I) -> T) =
object : Iterable<T> {
override fun iterator() = object : Iterator<T> {
val source = this@mapToIterable.iterator()
override fun hasNext(): Boolean = source.hasNext()
override fun next(): T = transform(source.next())
}
}
// variations of mapNotNull() that returns Iterable.
// it proxies iteration to avoid cost of create/update a list.
fun <I : Any?, T> Iterable<I>.mapNotNullToIterable(transform: (I) -> T?) =
this.mapToIterable(transform).filterNotNullToIterable()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment