Fix erroneous unused import flagging on custom destructure operators #142
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I noticed a bug with the unused import rule when I initially integrated in KtLint into one of my projects. It erroneously detected custom componentN operators as unused (which the auto formatter ended up removing and breaking my build :()
The Kotlin std library by default only provides
component1()
up tocomponent5()
, meaning that you can only destructure up to 5 values by default. See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html and search for "component5" for referenceSo if someone wants to destructure six values, i.e.:
(one, two, three, four, five, six) = someList
... the IDE will throw an error since
component6()
doesn't exist. To get around this you can write your own component6() method pretty easily:inline operator fun <T> List<T>.component6() = get(5)
.. and when this method is imported it's flagged by KtLint as unused since the unused import rule only checks for the default destructure methods (component1...5()).
To solve this I added a regex that'll match against componentN (where N is some number) and ignore the normal unused import checking.
I'm also open to suggestions if you think there is a better way of handling this case.