Using scala traits in a java code base

I am currently working on a code base with a mix of both Java and Scala. All of the apis have used dropwizard with scala but Scala support stopped at version 0.7.1. This is inhibiting us from upgrading to the latest version of dropwizard and also adopting Java 1.8. We have started re writing all of the Scala dropwizard apis back to java.

One of the problems we have encountered are that these dropwizard projects have a dependency on other projects written in scala. To minimize the amount of code to re write and get code released as early as possible, we only want to refactor what we need to enable us to get on the latest version of dropwizard and compile using java 8.

As Scala uses the adoption of traits quite heavily this has caused us some problems. Traits are very similar to Interfaces in Java but also provide implementation of its methods. If you try and implement the Scala trait in java code you will get a compile error as the trait has implemented behavior, as it’s not a regular Java interface.

Step-by-step guide

A quick and easy way around this is to create a wrapper abstract class in the Scala library which extends the trait. You can then extend this abstract class in your java code and get the implemented method behavior through this wrapper class. The example below allows you to call the concactStrings in the scala trait in your java code e.g.


// scala libary

package mathew

// the original trait

trait MathewTrait{

    def concatStrings(stringOne: String, stringTwo b) =  stringOne + stringTwo

}

// the wrapper class

abstract class MathewTraitWrapper extends MathewTrait

// java code

package mathew;

public class JavaMathew extends MathewTraitWrapper {

    public String JavaConcatStrings() {

    return concatStrings("Test message1","Test message 2");

   }

}

Leave a Reply

Your email address will not be published. Required fields are marked *