Asked 11 years, 3 months ago
Viewed 13k times
The default scala plugin task flow compiles Java before Scala so importing Scala sources within Java causes "error: cannot find symbol".
asked Apr 24, 2014 at 6:09
crizCraigcrizCraig8,93766 gold badges5959 silver badges5454 bronze badges
Java and Scala can be combined in the scala sources to have them compiled jointly, e.g.
sourceSets {
main {
scala {
srcDirs = ['src/main/scala', 'src/main/java']
}
java {
srcDirs = []
}
}
answered Apr 24, 2014 at 6:09
crizCraigcrizCraig8,93766 gold badges5959 silver badges5454 bronze badges
5If 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,
Separate the output folder of scala and java,
sourceSets {
main {
scala {
outputDir = file("$buildDir/classes/scala/main")
}
java {
outputDir = file("$buildDir/classes/java/main")
}
}
Add the scala output as a dependency for compileJava
,
dependencies {
compile files("$sourceSets.main.scala.outputDir")
}
answered Nov 8, 2017 at 9:59
1for gradle kotlin dsl you can use this piece
sourceSets {
main {
withConvention(ScalaSourceSet::class) {
scala {
setSrcDirs(listOf("src/main/scala", "src/main/java"))
}
}
java {
setSrcDirs(emptyList<String>())
}
}
test {
withConvention(ScalaSourceSet::class) {
scala {
setSrcDirs(listOf("src/test/scala", "src/test/java"))
}
}
java {
setSrcDirs(emptyList<String>())
}
}
}
answered Jul 24, 2019 at 7:49
RenkaiRenkai2,13122 gold badges1414 silver badges1919 bronze badges
Posting this update from the future here, as it would saved me a day.
gradle 6 doesn't support task dependencies modification, but here is what you can do:
// to compile Java after Scala
tasks.compileScala.classpath = sourceSets.main.compileClasspath
tasks.compileJava.classpath += files(sourceSets.main.scala.classesDirectory)
And here is documentation.
answered Mar 19, 2021 at 11:47
Start asking to get answers
Find the answer to your question by asking.
Ask questionExplore related questions
See similar questions with these tags.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4