Search code examples
javascalaintellij-ideaintellij-scala

How to import scala class into IntelliJ IDEA


I know this might not sound intelligent, but I am new to this and I really want to figure it out. I have been coding in JAVA recently and on the other hand have some function implemented within scala. I came across this article:

Interop Between Java and Scala

Which says it is possible to mix JAVA and scala. Since I am coding in IntelliJ IDEA, am wondering if there is anyway to bring in scala classes and use them within my JAVA code?

I have already included scala-library.jar using:

<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.10.3</version>
</dependency>

Any help or direction toward other useful links is much appreciated. Thanks.


Solution

    • if there is anyway to bring in scala classes and use them within my Java code?
    • is it possible to use scala classes inside Java or there is no way at all?

    Yes and yes. There are two scenarios: First you have an existing Scala library, then you can just use it in your existing Maven build as you have shown with the standard Scala library. Second (and I assume that is your actual question?) you have a project which contains both Java and Scala source code. In that case you need to compile both types of source files.

    In IntelliJ that would require that you somehow add the Scala façade to your project. Unfortunately, I am not a Maven expert, so I cannot tell you how this works with a Maven build.

    But if you use sbt and an sbt-based IntelliJ project, then IntelliJ will build the entire project with an sbt build server which is capable of compiling both your Java and Scala sources.

    You would have a directory structure like this:

    project
      build.properties
    build.sbt
    src
      main
        scala
          foo
            Foo.scala
        java
          foo
            Bar.java
    

    For example as build.properties:

    sbt.version=0.13.11
    

    As build.sbt:

    scalaVersion := "2.11.8"
    

    As Foo.scala:

    package foo
    
    class Foo {
      def test(): Unit = println("Hello from Scala!")
    }
    

    And as Bar.java:

    package foo;
    
    public class Bar {
        public static void main(String[] args) {
            final Foo f = new Foo();
            f.test();
        }
    }