pl0u
pl0u

Reputation: 375

Using Scala in Java - how to convert a Java Object to Option<Object>

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

Upvotes: 1

Views: 673

Answers (1)

Sohan Jain
Sohan Jain

Reputation: 2377

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

Upvotes: 4

Related Questions