Skip to content

Instantly share code, notes, and snippets.

@mayankmkh
Last active April 26, 2025 10:18
Show Gist options
  • Save mayankmkh/92084bdf2b59288d3e74c3735cccbf9f to your computer and use it in GitHub Desktop.
Save mayankmkh/92084bdf2b59288d3e74c3735cccbf9f to your computer and use it in GitHub Desktop.
Pretty Print Kotlin Data Class
fun Any.prettyPrint(): String {
var indentLevel = 0
val indentWidth = 4
fun padding() = "".padStart(indentLevel * indentWidth)
val toString = toString()
val stringBuilder = StringBuilder(toString.length)
var i = 0
while (i < toString.length) {
when (val char = toString[i]) {
'(', '[', '{' -> {
indentLevel++
stringBuilder.appendLine(char).append(padding())
}
')', ']', '}' -> {
indentLevel--
stringBuilder.appendLine().append(padding()).append(char)
}
',' -> {
stringBuilder.appendLine(char).append(padding())
// ignore space after comma as we have added a newline
val nextChar = toString.getOrElse(i + 1) { char }
if (nextChar == ' ') i++
}
else -> {
stringBuilder.append(char)
}
}
i++
}
return stringBuilder.toString()
}
@johannesrave
Copy link

johannesrave commented Oct 7, 2024

@thought-police-000 definitely love the buildString builder, i didn't know about that!

regarding the ): you could count the " as well in a "stringLevel" to decide whether one is still inside a string or to decrement the indentation level? adds complexity obviously :/

@teenriot
Copy link

@thought-police-000 I cleaned it up more, replaced "=" by " = " and ruined it again by packing the code :)

fun Any.toPrettyDebugString(indentWidth : Int = 4) = buildString {
    fun StringBuilder.indent(level : Int) = append("".padStart(level * indentWidth))
    var ignoreSpace = false
    var indentLevel = 0
    [email protected]().onEach {
        when (it) {
            '(', '[', '{' -> appendLine(it).indent(++indentLevel)
            ')', ']', '}' -> appendLine().indent(--indentLevel).append(it)
            ','           -> appendLine(it).indent(indentLevel).also { ignoreSpace = true }
            ' '           -> if (ignoreSpace) ignoreSpace = false else append(it)
            '='           -> append(" = ")
            else          -> append(it)
        }
    }
}

@doanvu2000
Copy link

công đức vô lượng

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