No Java util. List is implicitly converted to scala list

I'm interested in scala collection. Java conversions has a very basic problem I would expect the following code to work, but from Java util. Implicit conversion from list [string] to scala list [string] does not occur Why?

import collection.JavaConversions._
import java.util
class Test {
  def getStrings() : List[String] = {
    val results : java.util.List[String] = new java.util.ArrayList[String]()
    results
  }
}

I got a message from compi

type mismatch;
 found   : java.util.List[String]
 required: scala.collection.immutable.List[String]
    results
    ^

Solution

Convert to:

def getStrings() : Seq[String] = {
    val results : java.util.List[String] = new java.util.ArrayList[String]()
    results
  }

This is because the implicit function of the transformation is defined as:

implicit def asScalaBuffer[A](l: java.util.List[A]): mutable.Buffer[A]

It returns a mutable Buffer instead of scala collection. immutable. List. So it's wrong So the alternative is to use SEQ instead of list or convert it to immutable List, as follows:

def getStrings() : List[String] = {
    val results = new java.util.ArrayList[String]()     
    results.toList
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>