Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling Scala before / alongside Java with Gradle

Tags:

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

like image 683
crizCraig Avatar asked Apr 24 '14 06:04

crizCraig


People also ask

How do I run Scala with Gradle?

From inside the new project directory, run the init task using the following command in a terminal: gradle init . When prompted, select the 2: application project type and 5: Scala as implementation language. Next you can choose the DSL for writing buildscripts - 1 : Groovy or 2: Kotlin .

Does Gradle work with Scala?

Gradle supports version 1.6. 0 of Zinc and above. The Zinc compiler itself needs a compatible version of scala-library that may be different from the version required by your application. Gradle takes care of specifying a compatible version of scala-library for you.

Can Java and Scala work together?

Scala is compiled to Java bytecodes, and you can use tools like javap (Java class file disassembler) to disassemble bytecodes generated by the Scala compiler. In most cases, Scala features are translated to Java features so that Scala can easily integrate with Java.

Can't resolve all dependencies for configuration compile Gradle?

This is because of slow internet connection or you haven't configure proxy settings correctly. Gradle needs to download some dependencies , if it cant access the repository it fires this error. All you have to do is check your internet connection and make sure gradle can access the maven repository.


2 Answers

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.

like image 176
crizCraig Avatar answered Oct 03 '22 15:10

crizCraig


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") } 
like image 41
Longjun Avatar answered Oct 03 '22 15:10

Longjun