如何将 java.util.List 转换为 Scala 列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16162090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a java.util.List to a Scala list
提问by boycod3
I have this Scala method with below error. Cannot convert into a Scala list.
我有这个带有以下错误的 Scala 方法。无法转换为 Scala 列表。
def findAllQuestion():List[Question]={
questionDao.getAllQuestions()
}
type mismatch; found : java.util.List[com.aitrich.learnware.model.domain.entity.Question]
required:
scala.collection.immutable.List[com.aitrich.learnware.model.domain.entity.Question]
类型不匹配; 找到:java.util.List[com.aitrich.learnware.model.domain.entity.Question]
需要:
scala.collection.immutable.List[com.aitrich.learnware.model.domain.entity.Question]
采纳答案by Neil
import scala.collection.JavaConversions._
will do implicit conversion for you; e.g.:
会为你做隐式转换;例如:
var list = new java.util.ArrayList[Int](1,2,3)
list.foreach{println}
回答by Fynn
You can simply convert the List using Scala's JavaConverters
:
您可以简单地使用 Scala 转换列表JavaConverters
:
import scala.collection.JavaConverters._
def findAllQuestion():List[Question] = {
questionDao.getAllQuestions().asScala
}
回答by boycod3
def findAllStudentTest(): List[StudentTest] = {
studentTestDao.getAllStudentTests().asScala.toList
}
回答by Xavier Guihot
Starting Scala 2.13
, the package scala.collection.JavaConverters
is marked as deprecated in favor of scala.jdk.CollectionConverters
:
开始Scala 2.13
,该包scala.collection.JavaConverters
被标记为已弃用,以支持scala.jdk.CollectionConverters
:
import scala.jdk.CollectionConverters._
// val javaList: java.util.List[Int] = java.util.Arrays.asList(1, 2, 3)
javaList.asScala.toList
// List[Int] = List(1, 2, 3)
回答by Raymond Chenon
Import JavaConverters
, the response of @fynn was missing toList
导入JavaConverters
,@fynn 的响应丢失toList
import scala.collection.JavaConverters._
def findAllQuestion():List[Question] = {
// java.util.List -> Buffer -> List
questionDao.getAllQuestions().asScala.toList
}