can scala use the class( or something else ) defined in java file? Is it a must to first make these java files to a jar package and then use from scala?
2 Answers
Using Java from Scala is fairly seamless if you are using SBT.
I minimal example project showing free mixing of Scala and Java could look like:
- project root
build.sbtsrc/Hey.javaThere.scala
~~ build.sbt ~~
javaSource in Compile <<= baseDirectory(_ / "src")
scalaSource in Compile <<= baseDirectory(_ / "src")
~~ src/Hey.java ~~
public class Hey {
public static String yay = "Yay!!";
}
~ src/There.scala~~
object There extends App {
println(Hey.yay)
}
Then run There either by your IDE or by
$ sbt 'run-main There'
Similarly, if you have a Java library you want to use from your Scala project, you can use it as a Maven dependency without regard for whether it is Scala or Java:
~~ build.sbt ~~
libraryDependencies ++= Seq(
"com.neuronrobotics" % "nrjavaserial" % "3.7.5.1", // Java library
"org.scala-lang.modules" % "scala-xml_2.11" % "1.0.3" // Scala library
)
If you are using Maven as your build system, using libraries is as easy as in SBT. Mixing Scala and Java sources is a little trickier using Maven, and requires tapping onto a Maven lifecycle stage before compile.
Comments
Just complementing Owen's answer regarding SBT (it's actually easier):
- project root
- src
- main
- java
- Hey.java
- scala
- There.scala
- java
- main
- src
And then:
$ sbt run