How to provide Java interface for my Scala code?

I wrote a library in Scala. Now some Java programmers want to use it. Since they are not familiar with Scala collections such as Seqor ArrayBuffer, they will not be comfortable using it. I need to make some changes to my code.

Let me simplify my practical problem into 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 should I do to make a Java user feel comfortable when they interact with an object Person? 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 standard Java library.

I do not want 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.

, , - import scala.collection.JavaConverters._ .asJava . , Scala Java. , JavaConverters._ , , .

+4
1

Scala :

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

Java javaf, Scala scalaf ( ).

Play Scala API, Java, . . JavaResults Scala.

+2

All Articles