我有一个项目:
让我们说HelloWorld.scala就像:
package pkg2
object HelloWorld extends App {
println("Hello, world!")
}
如何从JHelloWorld调用HelloWorld:
package pkg1;
public class JHelloWorld {
public static void main(String[] args) {
//pkg2.HelloWorld.main(args);
}
}
编译器抱怨pkg2不存在......
我是否需要将scala代码放在不同的模块(jar文件)中并从那里开始?
感谢您的输入,但最后tutorial确实有所帮助。
虽然我使用maven-scala-plugin
但我有两个问题:
现在我的pom看起来像这样:
<build>
<sourceDirectory>src/main/scala</sourceDirectory>
<plugins>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<version>2.15.2</version>
<executions>
<!-- Run scala compiler in the process-resources phase, so that dependencies
on scala classes can be resolved later in the (Java) compile phase -->
<execution>
<id>scala-compile-first</id>
<phase>process-resources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<!-- Run scala compiler in the process-test-resources phase, so that
dependencies on scala classes can be resolved later in the (Java) test-compile
phase -->
<execution>
<id>scala-test-compile</id>
<phase>process-test-resources</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
答案 0 :(得分:0)
您应该检查一些事项。
首先,您必须确保项目中存在scala sdk。如果您正在使用IntelliJ IDEA,则只要转到scala文件,它就会发出警告。
.iml应该有这样的条目:
< orderEntry type="library" name="scala-sdk-2.11.7" level="application" />
如果您使用maven,则应添加如下条目:
< dependency>
< artifactId>scala-library</artifactId>
< groupId>org.scala-lang</groupId>
< version>${scala.version}</version>
</dependency>
一旦确定你有scala sdk,你应该在使用之前导入scala对象:
的pkg1
package pkg1
object HelloWorld extends App {
println("Hello, world!")
}
另外,不要忘记main方法应该使用new JHelloWorld()
则pkg2
package pkg2;
import pkg1.HelloWorld$;
public class JHelloWorld {
HelloWorld$ scalaObject = HelloWorld$.MODULE$;
public static void main(String argv[]) {
new JHelloWorld().scalaObject.main(argv);
}
}
以上应该可以正常使用
Connected to the target VM, address: '127.0.0.1:46179', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:46179', transport: 'socket'
Hello, world!
Process finished with exit code 0
答案 1 :(得分:0)