Compiling Scala before / alongside Java with Gradl

2019-02-03 07:19发布

问题:

The default scala plugin task flow compiles Java before Scala so importing Scala sources within Java causes "error: cannot find symbol".

回答1:

I found the following sourceSet config to fix the problem:

sourceSets {
    main {
        scala {
            srcDirs = ['src/main/scala', 'src/main/java']
        }
        java {
            srcDirs = []
        }
}

This because the scala source set can include both java and scala sources.



回答2:

If your java code use some external libraries like Lombok, using scala compiler to build java class will failed, as scala compiler don't know annotations.

My solution is to change the task dependencies, make compiling Scala before Java.

tasks.compileJava.dependsOn compileScala
tasks.compileScala.dependsOn.remove("compileJava")

Now the task compileScala runs before compileJava, that's it.

If your java code depends on scala code, you need to do two more steps,

  1. Separate the output folder of scala and java,

    sourceSets {
        main {
            scala {
                outputDir = file("$buildDir/classes/scala/main")
            }
            java {
                outputDir = file("$buildDir/classes/java/main")
            }
        }
    
  2. Add the scala output as a dependency for compileJava,

    dependencies {
        compile files("$sourceSets.main.scala.outputDir")
    }