Home » Checkstyle Kotlin

Checkstyle Kotlin

  • by
Checkstyle kotlin

1. Overview

In this article, we will learn the code style tools available for Kotlin. Before moving on, let’s understand that the checkstyle plugin is only for the Java language and right now it doesn’t support Kotlin. If you are using both Java and Kotlin together in your project, you might have already tried the checkstyle plugin and seen report generated only for Java files.

2. Kotlin code style tools

Widely known and easy-to-follow coding conventions are fundamental for any programming language. Now, let’s see the other Kotlin check style tools available for us to achieve it.

2.1. Ktlint style tool for Kotlin

Ktlint is a static analysis tool to analyze your project for any potential errors. It is a single tool with both linter and formatter included.

Linter: Automated checking of your source code for any programmatic and syntax errors, any deviations from a prescribed coding style, or using constructs known to be unsafe.

Formatter: Automatically format your code agreeing to set standards to make it quickly navigable and readable.

You can also add your own rule sets to discover potential bugs, check for anti-patterns, etc.

2.1.1. Setup

You can integrate ktlint plugin into your project by adding the plugin to your build script file. You can follow any of the two ways to add plugin:

  1. Using the apply plugin which works in all gradle versions
  2. new plugins api block which supports Gradle 2.1 and above
buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "org.jlleitschuh.gradle:ktlint-gradle:<current_version>"
  }
}

repositories {
  // Required to download KtLint
  mavenCentral()
}

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

repositories {
  // Required to download KtLint
  mavenCentral()
}

apply(plugin = "org.jlleitschuh.gradle.ktlint")
plugins {
  id "org.jlleitschuh.gradle.ktlint" version "<current_version>"
}

repositories {
  // Required to download KtLint
  mavenCentral()
}

If you want to do code style check for all of your subprojects, then apply the plugin to all project modules

subprojects {
    apply plugin: "org.jlleitschuh.gradle.ktlint" // Version should be inherited from parent

    repositories {
        // Required to download KtLint
        mavenCentral()
    }

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

    repositories {
        // Required to download KtLint
        mavenCentral()
    }    
    // Optionally configure plugin
    configure<org.jlleitschuh.gradle.ktlint.KtlintExtension> {
        debug.set(true)
    }
}

If you face any errors while integrating the ktlint plugin, refer to the compatible Gradle, Android gradle plugin and Kotlin versions for the ktlint version you are trying to use in the change log.

For example, ktlint 9.2.0 is compatible with Gradle 6.0.1, android Gradle plugin 3.5.0, and Kotlin 1.3.60. To avoid errors, you must have the right compatible versions.

2.1.2. KtlintCheck

To check the code style, run this task ktlintCheck in your project. It reports the code style errors in your project and auto-correct the errors.

In Android, you can run the task in the command line using gradlew ktlintCheck. For example, below is the sample errors reported by ktlintCheck. This task might not auto-correct all the errors.

> Task :app:ktlintAndroidTestSourceSetCheck FAILED
\app\src\androidTest\java\com\tedblob\myapplication\ExampleInstrumentedTest.kt:3:1: Imports mu
st be ordered in lexicographic order without any empty lines in-between
"plain" report written to \app\build\reports\ktlint\ktlintAndroidTestSourceSetCheck.txt

\app\src\androidTest\java\com\tedblob\myapplication\ExampleInstrumentedTest.kt:9:1: Wildcard i
mport (cannot be auto-corrected)

2.1.3. KtlintFormat

To run the formatter, use the task ktlintFormat in your project. It reports any formatting issues in your project and also auto-correct the errors.

In Android, you can run the task in the command line using gradlew ktlintFormat. This task might not auto-correct all the errors so you may need to manually fix them.

Below error is an example for ktLintFormat.

> Task :app:ktlintAndroidTestSourceSetFormat FAILED
\app\src\androidTest\java\com\tedblob\myapplication\ExampleInstrumentedTest.kt:5:1: Wildcard i
mport (cannot be auto-corrected)
"plain" report written to \app\build\reports\ktlint\ktlintAndroidTestSourceSetFormat.txt

Kotlin ktlint

2.1.4. Configuration

You can also configure ktlint to fit your requirements and it is optional.

import org.jlleitschuh.gradle.ktlint.reporter.ReporterType

ktlint {
    version = "0.22.0"
    debug = true
    verbose = true
    android = false
    outputToConsole = true
    outputColorName = "RED"
    ignoreFailures = true
    enableExperimentalRules = true
    additionalEditorconfigFile = file("/some/additional/.editorconfig")
    disabledRules = ["final-newline"]
    baseline = file("my-project-ktlint-baseline.xml")
    reporters {
        reporter "plain"
        reporter "checkstyle"
        reporter "sarif"
        customReporters {
            "csv" {
                fileExtension = "csv"
                dependency = project(":project-reporters:csv-reporter")
            }
            "yaml" {
                fileExtension = "yml"
                dependency = "com.example:ktlint-yaml-reporter:1.0.0"
            }
        }
    }
    kotlinScriptAdditionalPaths {
        include fileTree("scripts/")
    }
    filter {
        exclude("**/generated/**")
        include("**/kotlin/**")
    }
}
dependencies {
    ktlintRuleset "com.github.username:rulseset:master-SNAPSHOT"
    ktlintRuleset files("/path/to/custom/rulseset.jar")
    ktlintRuleset project(":chore:project-ruleset") 
}
import org.jlleitschuh.gradle.ktlint.reporter.ReporterType

configure<org.jlleitschuh.gradle.ktlint.KtlintExtension> {
    version.set("0.22.0")
    debug.set(true)
    verbose.set(true)
    android.set(false)
    outputToConsole.set(true)
    outputColorName.set("RED")
    ignoreFailures.set(true)
    enableExperimentalRules.set(true)
    additionalEditorconfigFile.set(file("/some/additional/.editorconfig"))
    disabledRules.set(setOf("final-newline"))
    baseline.set(file("my-project-ktlint-baseline.xml"))
    reporters {
        reporter(ReporterType.PLAIN)
        reporter(ReporterType.CHECKSTYLE)
        customReporters {
            register("csv") {
                fileExtension = "csv"
                dependency = project(":project-reporters:csv-reporter")
            }
            register("yaml") {
                fileExtension = "yml"
                dependency = "com.example:ktlint-yaml-reporter:1.0.0"
            }
        }
    }
    kotlinScriptAdditionalPaths {
        include(fileTree("scripts/"))
    }
    filter {
        exclude("**/generated/**")
        include("**/kotlin/**")
    }
}
dependencies {
    ktlintRuleset("com.github.username:rulseset:master-SNAPSHOT")
    ktlintRuleset(files("/path/to/custom/rulseset.jar"))
    ktlintRuleset(project(":chore:project-ruleset")) 
}

2.2. IDE code inspection

Besides ktlint, you can also use IDE code inspections. Android Studio and IntelliJ provide support for Kotlin code styling. You can configure them to auto-format your code to be consistent with the code style.

You can follow the below steps to enable the code style guide in the above IDEs

  1. Go to Settings | Editor | Code Style | Kotlin.
  2. Click Set from….
  3. Select Kotlin style guide. Do not select Kotlin obsolete IntelliJ IDEA codestyle.

IntelliJ obsolete default coding style differs from Kotlin’s official code style. If you are already using the IntelliJ codestyle, you can continue to do so.  

Therefore, you can use the IntelliJ codestyle by specifying the kotlin.code.style = obsolete in your project configured with maven or gradle as below and keeping “Kotlin obsolete IntelliJ IDEA codestyle” in the Settings | Editor | Code Style | Kotlin.

<properties> 
    <kotlin.code.style>obsolete</kotlin.code.style> 
</properties>
kotlin.code.style=obsolete

But to use the official code style in your project, add the below line to your gradle.properties file or maven pom.xml file.

<properties> 
    <kotlin.code.style>official</kotlin.code.style> 
</properties>
kotlin.code.style=official

3. Conclusion

To sum up, we have discussed the IDE code inspections and ktlint tool as alternatives to Checkstyle Kotlin.

Leave a Reply

Your email address will not be published. Required fields are marked *