Scala in a Java Maven Project

Learn how you can, with the help of a single plugin, use Scala in a Java project.

By  · Tutorial
Comment
Save
53.7K Views

probably the most painful thing for software developers is to be restricted in their choice of technology that they want to use in a development. you pay for a conference ticket, listen about new cool frameworks, development approaches, or tools… then you return to your office with huge enthusiasm and to try something on a real project. unfortunately, such initiative very frequently meets resistance from different sides: team members don’t want to learn something new, a manager thinks it is risky, a product owner hurries with a new release, etc.

well, to be honest, i described this situation too dramatically. of course, nobody will punish you for proposing to integrate something new in a project. another question is how to do it right.

today i want to discuss an interesting topic — how to use scala in a java project ? this case will be interesting for those developers who want to try scala in real scenarios. doesn’t matter what type of app you have: spring or spark or something else. i’m going to demonstrate how to integrate scala to a maven project .

let’s start!

abstract java maven project

let’s assume you are working on some java project. also, maven is used as project management tool. such project always looks like this:

maven-java-project-structure

as you can see, the project structure is pretty simple. it has a standard layout and only three java classes. let’s consider them:

package com.app.model;

public class book {

    private string name = null;
    private string author = null;

    public book(string name, string author) {
        this.name = name;
        this.author = author;
    }

    @override
    public string tostring() {
        return "book {" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                '}';
    }

    //getters & setters
}


then, the so-called data store:

package com.app.storage;

import com.app.model.book;
import java.util.arraylist;

public class bookstorage {

    private arraylist<book> books = new arraylist<book>();

    public bookstorage() {
        books.add(new book("white fang", "jack london"));
        books.add(new book("the sea-wolf", "jack london"));
        books.add(new book("the road", "jack london"));
        books.add(new book("the adventures of tom sawyer", "mark twain"));
        books.add(new book("around the world in 80 days", "jules verne"));
        books.add(new book("twenty thousand leagues under the sea", "jules verne"));
        books.add(new book("the mysterious island", "jules verne"));
        books.add(new book("the four million", "o. henry"));
        books.add(new book("the last leaf", "o. henry"));
    }

    public arraylist<book> getbooks() {
        return books;
    }
}


and finally runner:

import com.app.model.book;
import com.app.storage.bookstorage;

public class runner {

    public static void main(string[] args) {
        bookstorage storage = new bookstorage();
        storage.getbooks().stream().foreach((book b) -> system.out.println(b));
    }

}

don’t forget that we have the pom.xml file. it might contain some dependencies, plugins ,and build goals. this is actually not very important.

mixing scala into a java maven project

in order to make scala available inside of a java maven project, we need to use a maven plugin . yes, you understood correctly! there is only one required step. so let’s customize our pom.xml file:

...
<!-- make scala available in project. pay extra attention to the version -->
<dependencies>
    <dependency>
        <groupid>org.scala-lang</groupid>
        <artifactid>scala-library</artifactid>
        <version>2.11.7</version>
    </dependency>
</dependencies>

<build>
    <plugins>
<!-- this plugin compiles scala files -->
        <plugin>
            <groupid>net.alchim31.maven</groupid>
            <artifactid>scala-maven-plugin</artifactid>
            <executions>
                <execution>
                    <id>scala-compile-first</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>add-source</goal>
                        <goal>compile</goal>
                    </goals>
                </execution>
                <execution>
                    <id>scala-test-compile</id>
                    <phase>process-test-resources</phase>
                    <goals>
                        <goal>testcompile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
<!-- this plugin compiles java files -->
        <plugin>
            <groupid>org.apache.maven.plugins</groupid>
            <artifactid>maven-compiler-plugin</artifactid>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
<!-- this plugin adds all dependencies to jar file during 'package' command.
pay extra attention to the 'mainclass' tag. 
you have to set name of class with entry point to program ('main' method) -->
        <plugin>
            <artifactid>maven-assembly-plugin</artifactid>
            <version>2.5.3</version>
            <configuration>
                <descriptorrefs>
                    <descriptorref>jar-with-dependencies</descriptorref>
                </descriptorrefs>
                <archive>
                    <manifest>
                        <mainclass>scalarunner</mainclass>
                    </manifest>
                </archive>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

    </plugins>
</build>
...


after this update, you need to wait while maven downloads all this stuff and validates it. this is possible if you set auto-update for maven, but otherwise, you have to force it manually.

now we can use scala in the project. for this purpose, you need to create two new folders — ‘ src/main/scala ‘ and ‘ src/test/scala ‘. the scala maven plugin looks at these directories and compiles scala files within them.

let’s add some scala code in the project:

package com.app.service

import java.util
import scala.collection.javaconversions._

import com.app.model.book

object booksprocessor {

  def filterbyauthor(author: string)(implicit books: util.arraylist[book]) = {
    books.filter(book => book.getauthor == author)
  }

}


after this i, want to create an alternative entry point to the program:

import com.app.service.booksprocessor
import com.app.storage.bookstorage

object scalarunner extends app {

  implicit val books = (new bookstorage()).getbooks
  booksprocessor.filterbyauthor("jack london").foreach(b => println(b))

}

here is how the project looks after adding scala files:

java-maven-scala-project

try to run this code from the ide. it works as expected.

package scala-maven projects in a jar

what if you want to package this project in a jar file and then run it somewhere? for this, you need run the mvn package command or use its analogy in the ide. this action produces two jars in the ' target ' folder. you need to work with the one that has ‘ *-jar-with-dependencies.jar ‘ in its name.

scala-maven-project-run-from-command-line

in the screenshot above, i highlighted two options to run the jar. in the first onem you may specify which class you want to run. in the second one, we run the jar and it runs the default class specified in the pom.xml scalarunner .

by the way, you can generate executable jars by using the maven-assembly-plugin and its ' single ' goal.

summary

integrating scala in a java project is pretty straightforward. as you see, it can be done in 10 minutes. of course, it makes sense only if you already know at least the scala basics and know that with some help, you can develop a project more efficiently or rewrite existing functionality. everything depends on you.

Published at DZone with permission of Alexey Zvolinskiy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Comments