Created
April 14, 2022 20:30
-
-
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)
This file contains 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
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