Is there a tool for Scala to clean all the unused imports from all the code files? [closed]
Asked Answered
E

3

12

I believe my source code files feature many imports that are not used in the code (as I have a bad habit of copying them from existing to new files). When coding C# in Visual Studio (or, maybe, it's a feature of an add-on of it) one can wipe out all the unused imports in just a click. Is there an analogous tool for Scala? Would be cool if I could just point it to my sources directory and it would clean all the files inside it and all its subdirs and subdirs of them (etc).

Eggplant answered 14/10, 2011 at 12:27 Comment(0)
M
6

IntelliJ can automatically clean up imports, not just highlight them, and for the whole directory. The shortcut is Ctrl + Alt + O.

enter image description here

Melancholic answered 14/10, 2011 at 16:22 Comment(4)
I have never been brave enough to let it optimize imports for my complete project. Of course this is not sensible since you can always revert. But, does it work? Because automatic imports often fail.Foliar
@Foliar I've never tried the whole directory option either since I clean up files as I go. Sometimes automatic imports fail so you have to manually pick which one (usually when there's ambiguity) but I've never seen it remove an import that I'm using.Melancholic
In fact, for Scala it will remove imports which are required. This is the case for implicits, e.g. IntelliJ Scala plugin would like to remove my import com.bla.common.MonadInstances._ even my class won't compile without it. So, don't use it unless the plugin becomes more mature.Anatolic
btw, there is an open bug for the "aggressive" removal of used imports by scala plugin. youtrack.jetbrains.com/issue/SCL-6003Hear
I
4

I think Intellij marks unused imports gray. I don't think there is an automatic tool yet. Eclipse's and ensime's "organize imports" refactoring doesn't remove imports. You could of course always comment out individual imports and recompile.

Inverter answered 14/10, 2011 at 12:36 Comment(2)
Eclipse "organize imports" removes unused imports for me.Queenie
Organize imports is a feature of ScalaIDE since 2.0.0-beta6. scala-ide-portfolio.assembla.com/spaces/scala-ide/wiki/…Indivertible
A
1

Scalafix has a rewrite to remove unused imports: https://scalacenter.github.io/scalafix/#RemoveUnusedImports

add addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.5.0-M1") to your project/plugins.sbt

then run sbt "scalafix RemoveUnusedImports"

Agamemnon answered 28/7, 2017 at 0:32 Comment(4)
If you encounter an off-topic question, you should vote to close it instead of posting a link-only answer.Fir
@BaummitAugen corrected my post. I think the question is not off topic at all.Manaker
How so? Questions asking for off-site resources are explicitly off-topic.Fir
This doesn't work. Error message: "Not a valid key: scalafix (similar: scalaHome, ivy-scala, scalaVersion)"Claque

© 2022 - 2024 — McMap. All rights reserved.