Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix erroneous unused import flagging on custom destructure operators #142

Conversation

JelloRanger
Copy link
Contributor

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 to component5(), 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 reference

So 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.

- Devs can write custom componentN operators in order to allow
  destructuring blocks of > 5 values, i.e.

    inline operator fun <T> component6 = get(5)

which allows the following (which is NOT possible without the above
extension method):

   val (one, two, three, four, five, six) = someList
                                     ^--- component6() is imported to
make this possible

- In order to avoid marking these imports as unused we can ignore all
  imports that match componentX (where X is any number)
@JelloRanger JelloRanger changed the title Jelloranger/fix destructure operator unused import Fix erroneous unused import flagging on custom destructure operators Jan 26, 2018
@shyiko
Copy link
Collaborator

shyiko commented Jan 28, 2018

Hi Jacob. Thank you for the PR! It's perfect. ❤️

@shyiko shyiko merged commit 701c0b5 into pinterest:master Jan 28, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants