简体   繁体   中英

Scala's implicit conversion isn't working on java.util.List

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")

For your example to work, Scala would have to chain 2 implicit conversions (one juArrayList 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM