mjuarez mjuarez - 2 months ago 14
Scala Question

How to convert a Java Collection/List to a Scala seq?

I'm trying to instantiate a Kafka Scala case class from Java code, and it has the following signature:

case class OffsetFetchRequest(groupId: String,
requestInfo: Seq[TopicAndPartition],
versionId: Short = OffsetFetchRequest.CurrentVersion,
correlationId: Int = 0,
clientId: String = OffsetFetchRequest.DefaultClientId)


I'm able to send all the requested parameters, except for the
Seq[TopicAndPartition]
.

On the Java side, I have the following code:

OffsetFetchRequest offsetFetchRequest = new OffsetFetchRequest(
"someGroup",
topicAndPartitions,
(short)1,
1,
"clientId");


As expected, a
java.util.List
is not compatible with a Scala
Seq
. However, I've tried all types of conversion methods in
JavaConversions
and
JavaConverters
, and I can't find anything that fits this case.

How can I create a Scala
seq
from a normal
java.util.List
or even a
java.util.Collection
? Or am I approaching this incorrectly?

Answer

Use scala.collection.JavaConversions.asScalaBuffer which would convert Java list to Scala buffer, of which toList method can be used to convert to immutable seq.

Alternative, you could use CyclicIterator as well.