Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ does not sort Kotlin imports according to ktlint's expectations

When I select Code → Optimize Imports or Code → Reformat Code, the IntelliJ does optimize and sort imports, but even though I am using code style settings from Kotlin code style, the imports are not sorted in lexicographic order (not entirely at least). For example, this is the output produced:

import com.fasterxml.jackson.databind.ObjectMapper
import io.dropwizard.jackson.Jackson
import io.kotlintest.assertSoftly
import io.kotlintest.matchers.types.shouldBeNull
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.intellij.lang.annotations.Language
import java.time.Instant // This should not be at the bottom!!!

while this is what expected by ktlint:

import com.fasterxml.jackson.databind.ObjectMapper
import io.dropwizard.jackson.Jackson
import io.kotlintest.assertSoftly
import io.kotlintest.matchers.types.shouldBeNull
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import java.time.Instant // should be here instead
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.intellij.lang.annotations.Language

In other words, it seems the formatter always puts imports from java.* package at the bottom no matter what. Is there a way to make it be in line with what ktlint expects (and what would actually constitute lexicographic order)? Any hidden option I am missing or something?

I am using IntelliJ IDEA 2019.3.1 (Ultimate Edition) with the Kotlin plugin version 1.3.61-release-IJ2019.3-1. Version of ktlint is 0.36.0

like image 557
ysakhno Avatar asked Jan 21 '20 21:01

ysakhno


2 Answers

This is a bug/missing functionality in the Kotlin IDEA plugin: https://youtrack.jetbrains.com/issue/KT-10974. Please vote.

like image 190
Alexey Belkov Avatar answered Sep 27 '22 20:09

Alexey Belkov


You can change IntelliJ's import order for Kotlin to satisfy ktlint:

In Settings > Editor > Code Style > Kotlin you can change Import Layout by removing everything except import all other imports from the list:

Before:

Settings before

After:

Settings after

like image 40
Holger L Avatar answered Sep 27 '22 19:09

Holger L