https://kotlinlang.org logo
#getting-started
Title
# getting-started
t

tseisel

08/05/2022, 8:07 PM
How do you format your Kotlin code? Do you use the IDE format action before committing, or do you rely on a Git hook to run an external tool, such as ktlint or ktmft ? I'm also a TypeScript developer and I'm very satisfied with
prettier
, which IMHO formats code in a cleaner way than those 2 Kotlin tools. ktlint looks promising, but I don't like that it also lint-checks code ; I'd expect it to focus on formatting. Any Kotlin alternative?
l

Lawrence

08/05/2022, 8:18 PM
I like spotless with ktfmt. It also has prettier support but I am not sure if prettier supports Kotlin. There are also IDE plugins for ktfmt
t

Tim Oltjenbruns

08/05/2022, 8:22 PM
I run Detekt with autocorrect and the KtLint plugin before each gradle build.
Also have autoformat running in CI that way
There’s supposed to be a way to use editorconfig to plug in to KtLint - and I believe the IDE will use that too. I havn’t set that up.
o

Oliver.O

08/05/2022, 8:25 PM
Also using spotless, but with ktlint and the following configuration:
Copy code
spotless {
    // WORKAROUND respect .editorconfig – <https://github.com/diffplug/spotless/issues/142>
    val ktlintEditorConfig: Map<String, Any> = File("$rootDir/.editorconfig").useLines { lines ->
        val editorConfigSettingRegex = Regex("""^\s*(\w+)\s*=\s*([^#\s]*)""")
        lines.mapNotNull { line ->
            editorConfigSettingRegex.matchEntire(line)?.let { match ->
                val (name, value) = match.destructured
                name to (value.toIntOrNull() ?: value)
            }
        }.toMap()
    }
    kotlin {
        target("src/**/*.kt")
        ktlint().editorConfigOverride(ktlintEditorConfig)
    }
    kotlinGradle {
        ktlint().editorConfigOverride(ktlintEditorConfig)
    }
}
With ktfmt, I did not like fighting the existing coding standard and the IDE.
c

Charles Flynn

08/06/2022, 10:53 AM
IntelliJ's formatting is fine as long as everyone is set to the Kotlin Style Guide option. Beyond that we don't use anything. Just trust developers to commit well formatted code and it they don't reject it at code review. Personally speaking I'm not a fan of linters and in some work i did with TS I absolutely despised prettier.
o

Oliver.O

08/06/2022, 11:28 AM
I can relate. I'm also not a fan of tools trying to impose questionable rules on people. What I like about ktlint (together with the accompanying IDE plugin) is its auto-formatting, which is sometimes better than what the IDE does. And they try hard not to contradict the IDE formatter. Saves me time, does not hurt.
50 Views