Kotlin/kotlin-style-guide

Wildcard imports

xenomachina opened this issue ยท 9 comments

What is the feeling on wildcard imports?

I know the general consensus among Java programmers is that they are undesirable, but I'm wondering if the pros may outweigh the cons with Kotlin.

In Java, names other than class names are grouped in a class, so the whole set can be imported by importing a single class. In Kotlin, functions are often at the "top level". So in Java, where I might have a single import of "Foo" to get at "Foo.bar", "Foo.baz" and "Foo.quux", in Kotlin I'd have to import each name separately if they were defined at the top level. This is especially a problem with extension functions where (as far as I know) they have to appear at the top level.

While I do like knowing where names come from, IDEs generally make this even easier than looking at the imports, and even I, a die-hard vim user, use an IDE for working with Kotlin (but with a vim emulation plugin, of course).

yole commented

My feeling is simple: imports are for the IDE to manage. There are default settings; stick to them, leave your imports folded, use auto-import and "optimize imports on the fly".

Stick to the default IDE settings doesn't help when some people may use other tools or (eventually) even a different IDE. Unless those settings are actually documented other tools won't necessarily behave consistently with IntelliJ's defaults.

For example, ktlint doesn't like wildcard imports at all, but it seems that IntelliJ will use one if there are 5 imports from the same package. If that's a bug in ktlint then it would be nice to be able to point at some documentation that says "wildcard imports are ok if you're using 5 things from the same package" when reporting it.

IMHO just don't use wildcard imports. Easier for everyone, don't need to think when to use it and prevent from merge conflicts.

Rationale: Importing all classes from a package or static members from a class leads to tight coupling between packages or classes and might lead to problems when a new version of a library introduces name clashes.
- http://checkstyle.sourceforge.net/config_imports.html#AvoidStarImport

We ofen hear wildcard imports is evil, but why IDEA does not disable it by default

Wildcard imports are very useful for kotlin-android-extensions. It would be nice if the IDE could make an exception for these as "on-the-fly" optimizing makes it harder to use them.
(btw sorry if this is a very old thread)

The wildcard import prohibition was removed from Ktlint.

@Zhuinden is right. Ktlint has removed wildcard import rule at version 0.33.0

Detekt 1.0.0 still has NoWildcardImports rule, but we can define exceptions in another rule

    WildcardImport:
        active: true
        excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
        excludeImports: 'java.util.*,kotlinx.android.synthetic.*'