Created
July 29, 2019 12:40
-
-
Save belyaev-mikhail/ae1209fa177c757e23a8915a5c57d760 to your computer and use it in GitHub Desktop.
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
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