Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
inline class AppendScope(val appendable: Appendable) {
inline fun indent(indent: Int = 4, body: IndentScope.() -> Unit) {
IndentScope(indent).body()
}
}
inline fun AppendScope.appendln(value: CharSequence) = appendable.appendln(value)
inline class IndentScope(val indent: Int = 4) {
inline fun AppendScope.appendln(value: CharSequence) = appendable.append(" ".repeat(indent)).appendln(value)
inline fun indent(indent: Int = 4, body: IndentScope.() -> Unit) {
IndentScope(this.indent + indent).body()
}
}
inline fun prettyPrintTo(appendable: Appendable, body: AppendScope.() -> Unit) {
AppendScope(appendable).body()
}
fun main() {
val sb = StringBuilder()
prettyPrintTo(sb) {
appendln("fun foo() {")
indent {
appendln("val x = 2")
appendln("val y = 3")
appendln("run {")
indent(4) {
appendln("println(\"x = \$x\")")
}
appendln("}")
appendln("return x * y")
}
appendln("}")
}
println(sb)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment