I am facing an issue while using a StringBuilder to create a log message inside a loop in Kotlin.
for (person in Persons) {
val logMessage = StringBuilder()
.append("ID: ${person.Id}, ")
.append("Name: ${person.name}, ")
.append("Age: ${person.age}, ")
.toString()
HyperLog.d(
TAG,
logMessage
)}
Issue: I am getting a Ktlint error: A multiline expression should start on a new line (standard:multiline-expression-wrapping)
I tried adjusting the line breaks, but the error persists. Can anyone suggest how to fix this error and properly format the method chain?
Expected Outcome: I want to follow Kotlin’s best practices and avoid this Ktlint error while keeping the StringBuilder chain readable.
The StringBuilder
chain is the multiline expression. The KtLint rule requires you to start in on a new line.
In your code it starts as a variable assignment in the same line as the variable declaration:
val logMessage = StringBuilder()
.append("ID: ${person.Id}, ")
.append("Name: ${person.name}, ")
.append("Age: ${person.age}, ")
.toString()
To comply with the KtLint rule you need to put the expression on a new line instead:
val logMessage =
StringBuilder()
.append("ID: ${person.Id}, ")
.append("Name: ${person.name}, ")
.append("Age: ${person.age}, ")
.toString()
That's it, the KtLint warning should be gone now.
If you have the Ktlint plugin installed in Android Studio you can even let the plugin fix the issues for you. Just select one of the first two options in the settings and make sure the checkbox is ticked: