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

I have this Scala method with an error below. Cannot convert to 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]

+92
list scala scala-java-interop
Apr 23 '13 at 6:04 on
source share
5 answers
 import scala.collection.JavaConversions._ 

will make an implicit conversion for you; eg:.

 var list = new java.util.ArrayList[Int](1,2,3) list.foreach{println} 
+65
Oct 24 '15 at 1:16
source share

You can simply convert the List using Scala JavaConverters :

 import scala.collection.JavaConverters._ def findAllQuestion():List[Question] = { questionDao.getAllQuestions().asScala } 
+104
Apr 23 '13 at 8:07
source share
 def findAllStudentTest(): List[StudentTest] = { studentTestDao.getAllStudentTests().asScala.toList } 
+26
Oct 06 '14 at 5:02
source share

JavaConverters import, JavaConverters answer was missing toList

 import scala.collection.JavaConverters._ def findAllQuestion():List[Question] = { // java.util.List -> Buffer -> List questionDao.getAllQuestions().asScala.toList } 
+5
Oct 13 '17 at 15:20
source share

Starting with Scala 2.13 , the scala.collection.JavaConverters package scala.collection.JavaConverters 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) 
+1
Mar 28 '19 at 23:36
source share



All Articles