🪐

ktlint, detekt を利用している環境で定数のネーミングを PascalCase にするまでにやること

2025/02/06に公開

Kotlin の定数のネーミング

Kotlin のコーディング規約 では定数は SCREAMING_SNAKE_CASE で命名すると書いてあります。

Property names
Names of constants (properties marked with const, or top-level or object val properties with no custom get function that hold deeply immutable data) should use all uppercase, underscore-separated names following the (screaming snake case) convention:

引用: Coding conventions

ですが、 Compose の命名規則 では定数でも PascalCase を使用することが推奨されています。

Singletons, constants, sealed class and enum class values
Jetpack Compose framework development MUST name deeply immutable constants following the permitted object declaration convention of PascalCase as documented here as a replacement for any usage of CAPITALS_AND_UNDERSCORES. Enum class values MUST also be named using PascalCase as documented in the same section.
Library development SHOULD follow this same convention when targeting or extending Jetpack Compose.

App Development MAY follow this convention.

引用: API Guidelines for Jetpack Compose

本記事では ktlint, detekt を使用している環境で PascalCase に修正するためにやることを紹介します。

本題: 定数のネーミングを変えるためにやること

  1. ktlint
  2. detekt
  3. Intellij の設定

1. ktlint

.editorconfig に ktlint_property_naming_constant_naming = pascal_case を設定することでパスカルケースに設定することができます (参照)。

ただし こちらのルールは 1.5.0 で追加されたルール のため、ktlint のバージョンを忘れずに上げておきましょう!

build.gradle.kts
 ktlint {
+    version.set("1.5.0")
 }

2. detekt

Configuration for Compose のページにもあるように、 naming > TopLevelPropertyNaming > constantPattern[A-Z][A-Za-z0-9] に設定 します。

detekt.yml
naming:
  ...
  TopLevelPropertyNaming:
    active: true
    constantPattern: '[A-Z][A-Za-z0-9]*'

3. Intellij の設定

1,2 の設定だけだと Intellij の Inspections により警告が表示されてしまいます。
これを無効化するには 設定 > Editor > Inspections > Kotlin > Naming Conventions > Const property naming conventions のチェックを OFF にします。

またこの設定は .idea/inspectionProfiles/Project_Default.xml というファイルに保存されるみたいなのでこのファイルを gitignore に追加して コミットしておきましょうー

.gitignore
.idea/*
!.idea/inspectionProfiles/
!.idea/inspectionProfiles/Project_Default.xml

Discussion