Skip to content

Instantly share code, notes, and snippets.

@norswap
Created November 8, 2016 13:50
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 norswap/9b835b5dca98bfa38c03100b6829fe0a to your computer and use it in GitHub Desktop.
Save norswap/9b835b5dca98bfa38c03100b6829fe0a to your computer and use it in GitHub Desktop.
Showcasing the usefulness of inline receivers in Kotlin
inline fun <T, U> (() -> T?).map (crossinline f: (T) -> U): (() -> U?)
{
return { this()?.let(f) }
}
inline fun <T> (() -> T?).filter (crossinline pred: (T) -> Boolean): (() -> T?)
{
return {
var out = this()
while (out != null && !pred(out)) out = this()
out
}
}
inline fun <T> (() -> T?).toList(): List<T>
{
val out = arrayListOf<T>()
while (true) {
val item = this()
if (item == null) break
out.add(item)
}
return out
}
inline fun <T> Sequence<T>.supplier(): (() -> T?)
{
val iter = iterator()
return { if (iter.hasNext()) iter.next() else null }
}
fun test()
{
val seq = sequenceOf(1, 2, 3)
println(seq.supplier().map { it + 1 }.filter { it % 2 == 0 }.toList())
/* desugars to:
val out1 = ArrayList<Int>()
while (true) {
val tmp1 = if (seq.iter.hasNext()) iter.next() else null
var out2 = if (tmp1 != null) tmp1 + 1 else null
while (out != null && (out % 2 != 0)) {
val tmp2 = if (seq.iter.hasNext()) iter.next() else null
out2 = if (tmp2 != null) tmp2 + 1 else null
}
if (out2 == null) break
out1.add(item)
}
println(out1)
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment