Created
October 10, 2023 21:44
-
-
Save OndraZizka/7bbe63204ae36b08850517ce3da63fb7 to your computer and use it in GitHub Desktop.
A Stack-based Processing Context for Kotlin
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
class StackBasedContext( | |
val nestingStack: Deque<NestingLevel> = ArrayDeque(), | |
val problems: MutableList<Pair<String, List<NestingLevel>>> = mutableListOf(), | |
) { | |
override fun toString() = nestingStack.ifEmpty { listOf("(root)") }.joinToString("/") | |
fun addProblem(msg: String) { problems.add(msg to nestingStack.descendingIterator().asSequence().toList()) } | |
fun pushLevel(dataParam: KParameter): PopOnClose { nestingStack.push(NestingLevel(dataParam)); return PopOnClose() } | |
fun pushLevel(collectionIndex: Int): PopOnClose { nestingStack.push(NestingLevel(collectionIndex = collectionIndex)); return PopOnClose() } | |
fun popLevel(): NestingLevel = nestingStack.pop() | |
data class NestingLevel( | |
// ... Whatever your processing context needs on each level. | |
) { | |
override fun toString() = ... | |
} | |
/** Allows to leverage use { } with MapperContext. */ | |
inner class PopOnClose : AutoCloseable { | |
override fun close() { this@StackBasedContext.nestingStack.pop() } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment