Integrating Scala into an existing project in Java

SPIRiT_1984 picture SPIRiT_1984 · Dec 5, 2013 · Viewed 16.7k times · Source

we have a project written in Java. It is a maven project, that has jsp pages and a lot of java code:

  • servlets for handling user requests and dealing out responses.
  • classes of logic used by servlets in order to process the required logic.
  • classes of SQL generators used to connect to database and perform the specific queries required by the logic.

Well, we are looking towards Scala. For example, we use mappers in order to get a collection of entities from the database and after that transform this collection, filter it and return to the servlet. That seems like a good thing to do in Java. The question is - how can I integrate that into an existing project? Can I use in my logic files written in Java some Scala classes that again use the mapper files written in Java?

Answer

James Adam picture James Adam · Dec 5, 2013

I work on a mixed Java/Scala project right now (previously a Java-only project). Remember, there is no difference as far as the JVM is concerned between a .class file generated from javac vs. one generated from scalac.

For example: I implement Java interfaces and extend Java classes in Scala with no problems. I also instantiate Java beans and 'Scala' spring beans together in the same definition file (with scala beans having dependencies on java beans and vice-versa), and I have both Java and Scala beans coexisting together in a spring integration messaging pipeline.

The two languages inter-operate quite well, though where collections are concerned, you'll probably want to take a look at Scala's JavaConversions and JavaConverters objects.

For building, we use Ant (I'd personally prefer SBT for a new project, but if you're dealing with a pre-existing java project that uses ant, it's likely to be more trouble than it's worth to change build systems). To configure ant to compile scala files, have a look at this question.