Code Formatting in Kotlin using ktlint

Kotlin is a modern statically types programming language that is introduced by Google for primarily for Android development. So, you can write better and faster Android application with the help of Kotlin. Kotlin is a very cool language and to keep the coolness of the language you need to write the codes in the desired format. But if you are not familiar with how to write clean code using Kotlin then don’t worry you need not learn something to achieve this, instead, you just have to use ktlint that is used for the same purpose.

In this blog, we will learn how to write clean code or how to do code formatting in Kotlin using ktlint. So, let’s get started.

What is ktlint?

If we look at the definition of ktlint from its website then it says that:

ktlint is an anti-bikeshedding Kotlin linter with built-in formatter.

In simpler words, we can think of ktlint as a static code analysis tool that is used to analyze the Kotlin code for you. It will check if you have written the code by following the Kotlin code guidelines or not. If not, then it will suggest some changes for you. You can find the Kotlin coding guidelines from the Android Developer website.

ktlint does the following tasks:

  1. can lint your code and suggest some changes that can be made to have the code according to the Kotlin guidelines.
  2. can format your code (if some formatting is needed).
  3. you can define your rules for a particular coding style

The whole ktlint process can be divided into two parts:

  1. Linting: It checks if your code is written according to the Kotlin code guidelines or not. If not then it will show the changes that can be made to bring the code to the preferred style.
  2. Formatting: If your code is not written according to the Kotlin code guidelines then you can use the formatting option to auto-format the code for you to match to the desired code guidelines.

So, by using ktlint, you are saving your time as well as energy because you don’t have to check your code manually and that energy and time can be used in writing some logic for the application. Let’s see how we can integrate this ktlint in our project.

Using ktlint form command line

If you want to use ktlint from the command line then you have to first install ktlint in your machine and then use it. To install ktlint follow the below commands:

curl -sSLO https://github.com/pinterest/ktlint/releases/download/0.34.2/ktlint &&
  chmod a+x ktlint &&
  sudo mv ktlint /usr/local/bin/

On macOs or Linux, you can also use brew:

brew install ktlint

To use ktlint from the command line, you can apply the below commands:

# check the style of all Kotlin files inside the current dir (recursively)
# (hidden folders will be skipped)
$ ktlint --color
  src/main/kotlin/Main.kt:10:10: Unused import
  
# check only certain locations (prepend ! to negate the pattern) 
$ ktlint "src/**/*.kt" "!src/**/*Test.kt"

# auto-correct style violations
# (if some errors cannot be fixed automatically they will be printed to stderr) 
$ ktlint -F "src/**/*.kt"

# print style violations grouped by file
$ ktlint --reporter=plain?group_by_file
# print style violations as usual + create report in checkstyle format 
$ ktlint --reporter=plain --reporter=checkstyle,output=ktlint-report-in-checkstyle-format.xml

# install git hook to automatically check files for style violations on commit
# Run "ktlint installGitPrePushHook" if you wish to run ktlint on push instead
$ ktlint installGitPreCommitHook

Also, you can use help, to find more options of ktlint:

# find other things that can be done using ktlint
$ ktlint --help

Using ktlint in our project

To integrate ktlint in our project, we will be using ktlint gradle plugin in our project. There are two ways of integrating the ktlint plugin in our project. If you are using some older project with some older version of gradle then you can integrate ktlint by applying the below code:

buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "org.jlleitschuh.gradle:ktlint-gradle:<current_version>"
  }
}

apply plugin: "org.jlleitschuh.gradle.ktlint"

However, if you are using ktlint in your latest project with some latest version of gradle, then you can apply the plugin in your root level build.gradle file:

plugins {
  id "org.jlleitschuh.gradle.ktlint" version "<current_version>"
}

Also, at the same time, if you want to add ktlint to all your project modules then you can use this by writing the below lines of code:

subprojects {
    apply plugin: "org.jlleitschuh.gradle.ktlint" // Version should be inherited from parent
    
    // Optionally configure plugin
    ktlint {
       debug = true
    }
}

After adding these lines you can sync your project and start using ktlint.

ktlintCheck and ktlintFormat

After integrating ktlint in our project, our next task is to use Linting and Formatting functionalities in our project. For the sake of testing, I have written the code of MainActivity.kt file as below:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState) //note the spacing
        setContentView(R.layout.activity_main)
    }
}

To check if your code has some formatting errors or not, open the terminal of your Android studio and write the below command:

./gradlew ktlintCheck

This will start running the ktlintCheck task and it will show some build failed error if your code has some formatting errors. Not only that, it will show you the exact error that is being encountered i.e. unexpected indentation or unexpected blank line. Here, some lines can be auto-corrected while some lines can’t be auto-corrected. So, to fix the line that can be auto-corrected, you can use the below command in the terminal:

./gradlew ktlintFormat

To fix the error that cannot be fixed automatically, you have to fix it manually.

So, this is how you can use ktlint in your project for better code formatting and to arrange the Kotlin codes according to the preferred code styles. You can look at the ktlint page to have more idea about ktlin.

To learn more about some of the interesting facts and topics of Android development, you can read our blogs at the MindOrks website.

Keep Learning :)

Team MindOrks!