intelliJ IDEA 支持 sbt 不可变

intelliJ IDEA support for immutables with sbt

当使用java immutables library with IDEA and sbt时,编译和运行代码工作正常,但编辑器会在使用时给出"Cannot resolve symbol ..."和"Cannot resolve method ..."错误生成 类.

遵循 the documentation for setting up IDEs 对于 Maven 工作正常,但不能解决 sbt 的问题。

我们如何使用 sbt 在 IDEA 上为生成的源代码获得编辑器支持和代码完成?

首先,请按照 the documentation 中的说明进行操作。

To configure annotation processing in IntelliJ IDEA, use dialog Preferences > Project Settings > Compiler > Annotation Processors.

接下来,问题是 sbt 将我们生成的源文件放在 target/scala-2.n/classes/our/package 中。这是已编译的 .class 文件的目录,因此我们需要在其他地方生成源代码。编辑 IDEA 设置在这里对我们没有帮助,因此我们需要通过添加以下内容来编辑 build.sbt

// tell sbt (and by extension IDEA) that there is source code in target/generated_sources
managedSourceDirectories in Compile += baseDirectory.value / "target" / "generated_sources"
// before compilation happens, create the target/generated_sources directory
compile in Compile <<= (compile in Compile).dependsOn(Def.task({
  (baseDirectory.value / "target" / "generated_sources").mkdirs()
}))
// tell the java compiler to output generated source files to target/generated_sources
javacOptions in Compile ++= Seq("-s", "target/generated_sources")

最后我们需要告诉 IDEA 不应该忽略 target/ 中的所有内容,方法是删除该目录的排除项。要么转到文件 > 项目结构 > 项目设置 > 模块,单击 target 目录并取消选择 "Excluded"。或者,右键单击项目选项卡下的 target 目录,将目录标记为 > 取消排除。

此时您应该会看到编辑器支持在工作,如果没有,运行 sbt clean compile 以确保源已生成。


更新:最近的 sbt 版本中删除了 <<= 语法,您可以将上面的第二个指令替换为

// before compilation happens, create the target/generated_sources directory
compile in Compile := (compile in Compile).dependsOn(Def.task({
  (baseDirectory.value / "target" / "generated_sources").mkdirs()
})).value