How to convert a java.util.List to a Scala list

2019-01-10 07:25发布

I have this Scala method with below error. Cannot convert into a Scala list.

 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]

4条回答
放荡不羁爱自由
2楼-- · 2019-01-10 07:51

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
}
查看更多
做自己的国王
3楼-- · 2019-01-10 07:53
def findAllStudentTest(): List[StudentTest] = { 
  studentTestDao.getAllStudentTests().asScala.toList
} 
查看更多
迷人小祖宗
4楼-- · 2019-01-10 07:54

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

import scala.collection.JavaConverters._

def findAllQuestion():List[Question] = {
  questionDao.getAllQuestions().asScala
}
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-10 08:00
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}
查看更多
登录 后发表回答