-
-
Save mahdisml/89b8ce62d577fd1fc5b4c8c5ce652751 to your computer and use it in GitHub Desktop.
Pretty Print Kotlin Data Class
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
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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment