ktlint icon indicating copy to clipboard operation
ktlint copied to clipboard

Clarify violation in `filename` rule when class contains a single class and (extension) functions

Open FloEdelmann opened this issue 7 months ago • 1 comments

Expected Behavior

Given this file: https://github.com/streetcomplete/StreetComplete/blob/5dc586dc5bb1ca72e44d02232de78a14d571e09a/app/src/commonMain/kotlin/de/westnordost/streetcomplete/osm/WaysCrossingUtils.kt

It is called WaysCrossingUtils.kt, contains a single data class WaysCrossing(…), a public fun findNodesAtCrossingsOf(…) and some private functions and extension functions. Since it contains no WaysCrossing extension function, I expected the filename rule not to trigger.

To quote https://github.com/streetcomplete/StreetComplete/commit/4ed305009c42c3617a17bf06c57fa2a40e60d353#commitcomment-158225965:

The WaysCrossing is just the result data type of this utility function. Using the Utils postfix is more consistent here for this.

It could be named WaysCrossing if the API was like this:

data class WaysCrossing(...) {
   // ...

  companion object {
    fun find(barrierWays: Sequence<Way>, movingWays: Sequence<Way>, mapData: MapData) : WaysCrossing
  }
}

but it isn't, and I think it makes sense that it isn't.

Current Behavior

A lint violation is reported for the filename rule:

…/WaysCrossingUtils.kt:1:1: File 'WaysCrossingUtils.kt' contains a single class and possibly also extension functions for that class and should be named same after that class 'WaysCrossing.kt' (cannot be auto-corrected) (standard:filename)

Additional information

  • Current version of ktlint: 1.6.0

FloEdelmann avatar May 28 '25 14:05 FloEdelmann

See https://github.com/pinterest/ktlint/blob/32fd86f1d60a724f42affb2beafab055a2006478/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FilenameRule.kt#L24 for background information on this rule. The violation message is misleading indeed as it mentions "extension functions" explicitly. I could misinterpret the source documentation though.

To avoid this, you can either separate the class to another file, or supress the rule in this particular file with a @file annotation (see https://pinterest.github.io/ktlint/latest/faq/#how-do-i-suppress-errors-for-a-lineblockfile).

paul-dingemans avatar May 29 '25 17:05 paul-dingemans