2

When using the java immutables library with IDEA and sbt, compilation and running code works fine, but the editor will give "Cannot resolve symbol ..." and "Cannot resolve method ..." errors when using the generated classes.

Following the documentation for setting up IDEs works fine for Maven, but doesn't solve the issues for sbt.

How can we get editor support and code completion working for generated sources on IDEA with sbt?

4

1 回答 1

4

首先,请按照文档中的说明进行操作。

要在 IntelliJ IDEA 中配置注释处理,请使用对话框 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")

target/最后,我们需要通过删除该目录上的排除项来告诉 IDEA,不应忽略其中的所有内容。转到文件 > 项目结构 > 项目设置 > 模块,单击target目录并取消选择“排除”。或者,右键单击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
于 2017-03-02T23:59:29.420 回答