0

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 2

2

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.sbt
    • src/
      • Hey.java
      • There.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.

Sign up to request clarification or add additional context in comments.

Comments

0

Just complementing Owen's answer regarding SBT (it's actually easier):

  • project root
    • src
      • main
        • java
          • Hey.java
        • scala
          • There.scala

And then:

$ sbt run

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.