我测试了一个包含Scala和Java 16源代码的项目。Scala和Java源代码彼此依赖。
如果你的Java和Scala源代码相互依赖,那么你需要将这些源代码放在公共文件夹下。比如说
main/jvm
。
你可以将所有的Java
record
s放在
main/java
中。只要你的
record
s没有依赖于Scala代码,这将是有效的。否则,你将不得不将其拆分为多个模块,并根据依赖图进行微观管理。
Gradle版本是7.1,这个项目可以成功构建并运行(ScalaMain和JavaMain)。
build.gradle
plugins {
id 'java'
id 'scala'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
compileScala {
sourceCompatibility("16")
targetCompatibility("16")
}
sourceSets {
main {
java {
srcDirs = ['src/main/java']
}
scala {
srcDirs = ['src/main/jvm']
}
}
}
dependencies {
implementation 'org.scala-lang:scala-library:2.13.6'
}
main/java/TestJavaRecord.java
public record TestJavaRecord(int i) {}
main/jvm/TestScalaClass.scala
class TestScalaClass(val i: Int, val testJavaRecord: TestJavaRecord) {}
main/jvm/TestJavaClass.java
public class TestJavaClass {
public int i;
public TestScalaClass testScalaClass;
public TestJavaClass(int i, TestScalaClass testScalaClass) {
this.i = i;
this.testScalaClass = testScalaClass;
}
}
main/jvm/ScalaMain.scala
object ScalaMain extends App {
val testJavaRecord = new TestJavaRecord(5)
val testScalaClass = new TestScalaClass(5, testJavaRecord)
val testJavaClass = new TestJavaClass(5, testScalaClass)
println(testJavaRecord.i)
println(testScalaClass.testJavaRecord.i)
println(testJavaClass.testScalaClass.testJavaRecord.i)
}
main/jvm/JavaMain.java
public class JavaMain {
public static void main(String[] args) {
TestJavaRecord testJavaRecord = new TestJavaRecord(5);
TestScalaClass testScalaClass = new TestScalaClass(5, testJavaRecord);
TestJavaClass testJavaClass = new TestJavaClass(5, testScalaClass);
System.out.println(testJavaRecord.i());
System.out.println(testScalaClass.testJavaRecord().i());
System.out.println(testJavaClass.testScalaClass.testJavaRecord().i());
}
}
CountryResponse.java:5: illegal start of type declaration
与Scala无关,而与gradle有关。您需要正确配置gradle项目以能够编译Java 16代码。 - sarveshserisrcDirs
中有'src/main/java'
?如果您依赖Gradle Scala插件来处理Java 16文件,那么可以从Java的srcDirs
中删除它。 - sarveshseri'src/main/java'
,而不是两个地方都放。 - sarveshseribuild.gradle
。https://dev59.com/EaLia4cB1Zd3GeqPhVV9 - NikMashei