4

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
  • Unfortunately, it looks like a manual task: setting up a Java-compatible API in a separate package that would wrap your Scala API. The more 'Scala-idiomatic' your base API is, the more that adapter layer is actually needed... Commented Jun 26, 2015 at 7:15

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.