简体   繁体   English

不会发生java.util.List到scala List的隐式转换

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

I have very basic problem with scala.collection.JavaConversions. 我对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. 我希望以下代码可以工作,但是从java.util.List [String]到scala List [String]的隐式转换不会发生。 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 我从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 . 它返回一个mutable.Buffer而不是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: 所以替代方法是使用Seq而不是List或将其转换为immutable.List ,如下所示:

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

您需要做的就是导入:

import scala.collection.JavaConversions._

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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