Android Studio does not rearrange import in lexicographic order

Viewed 7479

Given the following imports

import javax.inject.Inject
import kotlinx.android.synthetic.main.fragment.*

Android Studio rearrange to the following when pressing control + option + o

import kotlinx.android.synthetic.main.fragment.*
import javax.inject.Inject

Which is not in lexicographic order. My pre-commit hook running ktlint then fails because of this. Is there any way to fix this issue?

6 Answers

The latest IntelliJ IDEA / Android Studio might not be able to conform to full specifications in the Android Kotlin style guide. So, currently, there is no straight-forward way of arranging the imports lexicographic order in IntelliJ IDEA / Android Studio.

For now, you may want to disable this check for Klint by disabling 'import ordering' in the .editorconfig file in the root of your project:

[*.{kt,kts}]
disabled_rules = import-ordering

This will disable the check in your project.

IntelliJ IDEA / Android Studio doesn't let you order imports alphabetically, neither in Java nor in Kotlin.
However Java features an Import layout section, which can give you some control. But still it's impossible to have an exact ordering, as you want it.

enter image description here

This isn't available for Kotlin is now available in Kotlin too. You can look at https://youtrack.jetbrains.com/issue/KT-10974

Its strange behavior but if you delete all from Import aliases separately you will get lexicographical order

Before: enter image description here After: enter image description here

You could disable import ordering for that file.

I had this:

import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import java.io.Serializable
import kotlinx.android.parcel.Parcelize

Ktlint reordered it that way, but check continued to fail:

Had to add the ignore in the first line:

import android.os.Parcelable // ktlint-disable import-ordering
import com.google.gson.annotations.SerializedName
import java.io.Serializable
import kotlinx.android.parcel.Parcelize

If you are in IntelliJ/Android Studio, usually just clicking Code -> Optimize Imports is enough to fix it

That’s just a linting error if I recall correctly

I know this is old, and I did manage to fix the issue by adding // ktlint-disable import-ordering but eventually I found a better solution. If you have command line ktlint installed, you can run the ktlint --android -F terminal command on your android source code folder and it will automatically fix this issue. The --android part is very important, using the ktlint -F command, without the android part, will fix some ktlint issues but not his one.

Related