How to provide a Java-friendly interface for my Scala code?

392 views Asked by At

I have written a library in Scala. Now, some Java programmers wants to use it. Since they are not familiar with Scala collections like Seq or ArrayBuffer, they will not be comfortable using it. I need to make some changes to my code.

Let me simplify the practical problem of mine to a simple class:

class Person(val name: String, val age: Int, val friends: Set[Person]) {
  def friendNamesAndAges: ArrayBuffer[(String, Int)] =
    friends.map(x => (x.name, x.age))[ArrayBuffer]
}

What do I do to make my Java user feel comfortable when they interact with a Person object? Ideally, their code would look like

import java.util.HashSet;
import java.util.ArrayList;

...

Person somePerson = // some person
HashSet<Person> a = somePerson.friends();
ArrayList<Pair<String, Int>> b = somePerson.friendNamesAndAges();

and then they can happily do whatever they want because the collections are from the Java standard library.

What I don't want is this:

import scala.*;
import scala.collection.immutable.Set;
import scala.collection.mutable.ArrayBuffer;

...

Person somePerson = // some person
Set<Person> a = somePerson.friends();
ArrayBuffer<Tuple2<String, Object>> b = somePerson.friendNamesAndAges();

with which a Java programmer may not feel comfortable.

One way that I know to do this is to import scala.collection.JavaConverters._, and add .asJava to the collections. But I will end up with two functions of the same name returning a Scala collection and a Java collection. Besides, JavaConverters._ does not have a converter for tuples like the one I have in the example.

1

There are 1 answers

0
bjfletcher On BEST ANSWER

I'd have this Scala code:

javaf(b: ArrayList[Pair[String, Int]) =
  scalaf(b.map(p => (p.getLeft, p.getRight))

Then Java people would call javaf whereas Scala people would call scalaf (in a separate place).

That is exactly how Play writes some code in Scala and provides Java-friendly API using it. See for example the JavaResults Scala class.