1

I'm writing in java, and I need to use external library that is written in scala. In particular, I need the following constructor:

new PartitionMetadata(partitionId: Int, leader: Option[Broker], replicas: Seq[Broker], isr: Seq[Broker] = collection.this.Seq.empty[Nothing], errorCode: Short = kafka.common.ErrorMapping.NoError)

I was able to convert all but the leader : Option[Broker] and the Seq parameters in my java code:

partitionMetadata = new kafka.api.PartitionMetadata(
  partitionId, leader.getBroker(),(Seq)brokerReplicas, (Seq)brokerIsr, errorCode);

I'm getting the following error in my editor:

'PartitionMetadata(int, scala.Option<kafka.cluster.Broker>, scala.collection.Seq<kafka.cluster.Broker>, scala.collection.Seq<kafka.cluster.Broker>, short)' in 'kafka.api.PartitionMetadata'
cannot be applied to (int, kafka.cluster.Broker, scala.collection.Seq, scala.collection.Seq, short)

Is it possible to use a Scala constructor in Java? Also, how do I convert a Java Object (leader) to a Option?

Lastly, am I converting the ArrayList -> Scala.collection.Seq fields correctly?

Thanks

1 Answer 1

4

Yes, it's possible to use this scala constructor in Java. The error message from your editor gives you a hint: it expects a scala.Option<kafka.cluster.Broker> as the second argument.

You can create that scala.Option as follows: scala.Option.apply(leader.getBroker())

Also, you shouldn't just cast your java array lists to scala.Seq. Instead, check out scala.collection.JavaConversions

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

2 Comments

thanks for the answer! From the conversion, it looks like there is no way to convert any type into scala.collection.Seq Is there another method for conversion that I use instead? Is there a way to create an empty scala.collection.Seq in Java, then subsequently populate it with my elements?
You can use asScalaBuffer. Check out its method header: it takes in a java.util.List (which an ArrayList satisfies), and returns a scala.collection.mutable.Buffer (which extends Seq)

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.