Created
December 5, 2020 20:02
-
-
Save tateisu/bc86965340e238c73f3f9adefc89d2e3 to your computer and use it in GitHub Desktop.
mapNotNullToIterable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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