Skip to content

Instantly share code, notes, and snippets.

@orangy
Created July 22, 2014 15:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orangy/dbb956d6edb4c90d4107 to your computer and use it in GitHub Desktop.
Save orangy/dbb956d6edb4c90d4107 to your computer and use it in GitHub Desktop.
trait SelectResult<T> {
val take: Boolean
val value: T
class object {
fun take<T>(value: T) = object : SelectResult<T> {
override val value: T = value
override val take: Boolean = true
}
fun skip<T>() = object : SelectResult<T> {
override val value: T
get() = throw UnsupportedOperationException("Cannot get value from skip object")
override val take: Boolean = false
}
}
}
val <T> indexed: (T) -> SelectResult<Pair<Int, T>>
get() {
var index = 0
return { SelectResult.take(index++ to it) }
}
val <T : Any> notNull: (T?) -> SelectResult<T>
get() = {
if (it != null) SelectResult.take(it) else SelectResult.skip()
}
inline fun <T, R> Iterable<T>.foreach(selector: (T) -> SelectResult<R>, body: (R) -> Unit) {
for (element in this) {
val selected = selector(element)
if (selected.take)
body(selected.value)
}
}
fun fn(items: List<String>) {
items.foreach<String, String>(notNull) { value ->
println("$value")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment