如何将 java.util.List 转换为 Scala 列表

我有这个 Scala 方法,错误如下。无法转换成 Scala 列表。

 def findAllQuestion():List[Question]={
questionDao.getAllQuestions()
}

类型不匹配; 发现: java.util.List[com.aitrich.learnware.model.domain.entity.Question]要求: scala.collection.immutable.List[com.aitrich.learnware.model.domain.entity.Question]

81171 次浏览

You can simply convert the List using Scala's JavaConverters:

import scala.collection.JavaConverters._


def findAllQuestion():List[Question] = {
questionDao.getAllQuestions().asScala.toList
}
def findAllStudentTest(): List[StudentTest] = {
studentTestDao.getAllStudentTests().asScala.toList
}
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}

Import JavaConverters , the response of @fynn was missing toList

import scala.collection.JavaConverters._


def findAllQuestion():List[Question] = {
//           java.util.List -> Buffer -> List
questionDao.getAllQuestions().asScala.toList
}

Starting Scala 2.13, the package scala.collection.JavaConverters is marked as deprecated in favor of 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)