Skip to content

Instantly share code, notes, and snippets.

@Mahoney
Created December 8, 2023 11:49
Show Gist options
  • Select an option

  • Save Mahoney/9f7ecc0640d70f746034e5f05d962b6b to your computer and use it in GitHub Desktop.

Select an option

Save Mahoney/9f7ecc0640d70f746034e5f05d962b6b to your computer and use it in GitHub Desktop.
Sort of Higher Kinded Types in Kotlin
fun <A, B, C, R> inTransaction(work: (A, B, C) -> R): (A, B, C) -> R {
// do something
return { a: A, b: B, c: C ->
// do something
try {
work(a, b, c)
} finally {
// do something
}
}
}
inline fun <A, B, R> inTransaction(crossinline work: (A, B) -> R): (A, B) -> R = removeAParameter(::inTransaction, work)
inline fun <A, R> inTransaction(crossinline work: (A) -> R): (A) -> R = removeAParameter(::inTransaction, work)
inline fun <. R> inTransaction(crossinline work: () -> R): () -> R = removeAParameter(::inTransaction, work)
inline fun <A, B, R> removeAParameter(
original: ((A, B, Unit) -> R) -> ((A, B, Unit) -> R),
crossinline work: (A, B) -> R
): (A, B) -> R {
val adaptedWork = original { a: A, b: B, _: Unit -> work(a, b) }
return { a, b -> adaptedWork(a, b, Unit) }
}
inline fun <A, R> removeAParameter(
original: ((A, Unit) -> R) -> ((A, Unit) -> R),
crossinline work: (A) -> R
): (A) -> R {
val adaptedWork = original { a: A, _: Unit -> work(a) }
return { a -> adaptedWork(a, Unit) }
}
inline fun <R> removeAParameter(
original: ((Unit) -> R) -> ((Unit) -> R),
crossinline work: () -> R
): () -> R {
val adaptedWork = original { _: Unit -> work() }
return { adaptedWork(Unit) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment