0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

importの順序でLint(ktlintなど)に指摘されることがあります。
特にCIでは失敗するのに、ローカルでは問題なく見えるケースもあり、地味に手が止まりやすいポイントです。

そこで本記事では、import順序をLint基準に統一する方法について、備忘録的にまとめておこうと思います。

原因

この問題の原因はシンプルで、以下のズレによって発生します。

  • Android Studio(IDE)のフォーマット
  • ktlintなどのLintルール

それぞれが異なるimport順序を採用しているため、整形結果に差分が生まれます。

対応方法

.editorconfigでimport順序を統一する

以下の設定を.editorconfigに追加します。

[*.{kt,kts}]
ij_kotlin_imports_layout=*,java.**,javax.**,kotlin.**,^
ij_kotlin_name_count_to_use_star_import=999
ij_kotlin_packages_to_use_import_on_demand=

設定のポイント

  • ij_kotlin_imports_layout
    importの並び順を定義します。
    * はその他のimport、^ はalias importを表します。

  • ij_kotlin_name_count_to_use_star_import=999
    ワイルドカードimport(*)の使用を抑制します。

  • ij_kotlin_packages_to_use_import_on_demand=
    特定パッケージでのワイルドカードimportを無効化します。


ktlint側の設定

ktlintを利用している場合は、基本的に.editorconfigを参照するため、以下の設定のみで問題ありません。

ktlint {
    android = true
}

Android Studio側の確認

通常は.editorconfigによってIDEの挙動も統一されますが、もし整形結果が一致しない場合は以下を確認します。

Settings > Editor > Code Style > Kotlin > Imports

動作確認

以下のコマンドでimport順序が自動整形されます。

./gradlew ktlintFormat

CIと同じルールで整形されるため、差分が出ないことを確認できます。

さいごに

桜がだいぶ咲いてきましたね🌸

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?