Skip to content

Instantly share code, notes, and snippets.

@bnorm
Created December 20, 2017 20:33
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bnorm/71c7973b4b3f928e855a183a3e56c791 to your computer and use it in GitHub Desktop.
Save bnorm/71c7973b4b3f928e855a183a3e56c791 to your computer and use it in GitHub Desktop.
Turns a Kotlin Data class toString() into formatted JSON-like output
fun Any?.toIndentString(): String {
val notFancy = toString()
return buildString(notFancy.length) {
var indent = 0
fun StringBuilder.line() {
appendln()
repeat(2 * indent) { append(' ') }
}
for (char in notFancy) {
if (char == ' ') continue
when (char) {
')', ']' -> {
indent--
line()
}
}
if (char == '=') append(' ')
append(char)
if (char == '=') append(' ')
when (char) {
'(', '[', ',' -> {
if (char != ',') indent++
line()
}
}
}
}
}
@erksch
Copy link

erksch commented Mar 11, 2022

refactored version

fun String.toIndentString(): String = buildString(length) {
    var indent = 0

    fun line() {
        appendLine()
        repeat(2 * indent) { append(' ') }
    }

    this@toIndentString.filter { it != ' ' }.forEach { char ->
        when (char) {
            ')', ']', '}' -> {
                indent--
                line()
                append(char)
            }
            '=' -> append(" = ")
            '(', '[', '{', ',' -> {
                append(char)
                if (char != ',') indent++
                line()
            }
            else -> append(char)
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment