Reputation: 433
I'm a scala newer, and i'm trying to use scala in my java project. I want to treat java.util.List
like Array
in scala code, and i know a little abount implicit conversion and think it may help me. But after a implicit conversion converting java.util.ArrayList[String]
to Array[String]
defined. My code still doesn't work. Here is my code, can anyone give me some suggesions.
implicit def collection2Arr(collection:java.util.ArrayList[String]) :Array[String] = {
return collection.toArray(new Array[String](collection.size()))
}
val arrayList = new util.ArrayList[String]()
arrayList.map(x=>x+"1")
Upvotes: 0
Views: 144
Reputation: 3482
For your example to work, Scala would have to chain 2 implicit conversions (one j.u.ArrayList
to scala.Array
, another from scala.Array
to ArrayOps
. In general, such technique would bring exponential number of possibilities to check (traverse over all possible chains of implicit conversions) and would make developers literally unable to tell which one worked. Thus, Scala checks only for 1 possible conversion, and, since there's no map
neither in ArrayList
nor in Array
, fails.
Answering your questions, your should use JavaConverters
:
scala> val l = new ArrayList[String]()
l: java.util.ArrayList[String] = []
scala> import scala.collection.JavaConverters._
import scala.collection.JavaConverters._
scala> l.asScala
res0: scala.collection.mutable.Buffer[String] = Buffer()
scala> l.asScala.toArray
res1: Array[String] = Array()
scala> l.asScala.toArray.map(x => x + "1")
res2: Array[String] = Array()
Upvotes: 4