简体   繁体   中英

Implicit conversion of java.util.List to scala List does not occur

I have very basic problem with scala.collection.JavaConversions. I would expect that following code would work but implicit conversion from java.util.List[String] to scala List[String] does not happen. 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 get following message from compi

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

Convert it to:

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

This is because, the implicit function for the conversion is defined as:

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

It returns a mutable.Buffer and not scala.collection.immutable.List . Hence the error. So alternative is to use a Seq instead of List or convert it to a immutable.List as below:

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

您需要做的就是导入:

import scala.collection.JavaConversions._

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