Created
July 22, 2014 15:01
-
-
Save orangy/dbb956d6edb4c90d4107 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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