1

I have a java list

scala.collection.mutable.ListBuffer<ScalaMainObject.Attribute12> scalaAtr;
 ScalaMainObject.Attribute12 atr;
ScalaMainObject.BaseEntity12 be1;
for( int i= 0; i<datapodDet.getAttributes().size();i++){
            datapodDet.getAttributes().get(i).getAttributeId();
            datapodDet.getAttributes().get(i).getType();
            datapodDet.getAttributes().get(i).getName();
            datapodDet.getAttributes().get(i).getDesc();
            be1 = new ScalaMainObject.BaseEntity12(datapodDet.getAttributes().get(i).getAttributeId().toString(),datapodDet.getVersion(),datapodDet.getAttributes().get(i).getName()
                    ,datapodDet.getAttributes().get(i).getDesc(),datapodDet.getActive());
            atr = new ScalaMainObject.Attribute12(datapodDet.getAttributes().get(i).getType(), be1);
            scalaAtr.add(atr);
}

Now my scala case class is ,

object ScalaMainObject {

  case class Datapod12(baseEntityVal:BaseEntity12,attr: scala.collection.mutable.ListBuffer[Attribute12]){

  }
}

I want to convert this java list to scala.collection.mutable.ListBuffer[Attribute12] from java code and after that will invoke a scala method.

But I am not able to convert java list to scala listbuffer. Please advice!!

Rhea
  • 381
  • 1
  • 7
  • 22

1 Answers1

4

You can convert java collections to scala collections or vice versa with using import collection.JavaConverters._

This provides implicit functions to do conversions.

scala> val jlist = new java.util.LinkedList[Int]()
jlist: java.util.LinkedList[Int] = []

scala> jlist.add(1)
res7: Boolean = true

scala> jlist.add(2)
res8: Boolean = true

scala> import collection.JavaConverters._
import collection.JavaConverters._

scala> jlist.asScala
res9: scala.collection.mutable.Buffer[Int] = Buffer(1, 2)
Fatih Donmez
  • 4,319
  • 3
  • 33
  • 45
  • No I am not able to convert javaList to scala List. I tried to do, (in java class) ScalaMainObject.Datapod12 datapodDet1 = new ScalaMainObject.Datapod12(be,scala.collection.JavaConversions.asScalaBuffer(scalaAtr)); But it is giving error – Rhea Aug 26 '16 at 19:04
  • To understand better; check this http://stackoverflow.com/questions/8301947/what-is-the-difference-between-javaconverters-and-javaconversions-in-scala – Fatih Donmez Aug 27 '16 at 07:28