We're using the official Kotlin style guide to format our source code.
To enforce this, we do have a Gradle task for checking that the style guide is met and another task for formatting the code base.
You can run these tasks from the command line like this:
./gradlew ktLintCheck
./gradlew ktLintFormat
These tasks have also been added as run configurations to the IDEA project, so that you can run them directly from IntelliJ. Just select the respective task and hit the green play icon.
When inspecting errors found by those tasks, it is important to select the top-level item in the run view, otherwise you won't be able to find the actual errors that the task found. By default a different item is selected in that view. Select the topmost item as in this screenshot:
Wildcard imports
The Kotlin style guide does not allow wildcard imports. When getting rid of them, you can reimport the objects that are not being imported clicking the word in the editor, press Alt-Enter
and select import
.
For some reason, when using mutableStateOf
, it does not suffice to import
import androidx.compose.runtime.mutableStateOf
but we also need to add those two imports, which does not happen automatically:
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
Git hooks
If you want to avoid committing or pushing code that doesn't comply with the coding conventions, it can help to add a git hook.
For example to create a hook that prevents you from pushing commits that fail ./gradle ktlintCheck
, add the following script at .git/hooks/pre-push
:
#/bin/bash
./gradlew ktlintCheck
if [ $? -ne 0 ]; then
echo "ktlint failed"
exit 1
fi
exit 0
Similarly, you can create a script at .git/hooks/pre-commit
to check the coding conventions on every commit.
Files not ending with line breaks
The linter requires every file to end with a line break. IntelliJ doesn't add those by default, so to force it to do that, enable the following setting:
Settings
→ Editor
→ General
→ On Save
→ Ensure every saved file ends with a line break
Save Actions Plugin
Speaking about performing things during saving, the Save Actions Plugin can be installed into IntelliJ and configured to Optimize imports and reformat files on save. It can be downloaded via the Plugins section in the Settings screen. Once installed, there's a separate configuration item in the Settings navigation for Save Actions and one needs to activate save actions, and enable "Optimize imports" and "Reformat file".