Skip to content

Instantly share code, notes, and snippets.

@DevSrSouza
Created April 14, 2022 20:30
Show Gist options
  • Save DevSrSouza/f1d8f19dc0dd5d39aeb640062ea1eea2 to your computer and use it in GitHub Desktop.
Save DevSrSouza/f1d8f19dc0dd5d39aeb640062ea1eea2 to your computer and use it in GitHub Desktop.
Generate withContext functions for Kotlin Context (Context does not work with Generics yet)
fun main(args: Array<String>) {
val generatedWithGenericCount = 16
fun generateWithFunction(contextsCount: Int): String {
val generics = (1..contextsCount).map { "T$it" }.joinToString(", ")
val params = (1..contextsCount).map { "param$it: T$it" }.joinToString(",\n")
val contexts = "context(" + (1..contextsCount).map { "T$it" }.joinToString(", ") + ")"
val withBlocks = (1..contextsCount).map { "with(param$it){" }.joinToString(" ")
val withBlocksEnd = (1..contextsCount).map { "}" }.joinToString(" ")
return """
fun <R, $generics> withContext(
${params},
block: $contexts () -> R,
): R {
return $withBlocks
block()
$withBlocksEnd
}
""".trimIndent()
}
val resultFile = (1..generatedWithGenericCount).map { generateWithFunction(it) }.joinToString("\n\n")
File("contextWith.kt").writeText(resultFile)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment