108
votes

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]

5
Folks looking at this question might find this other question of interest: stackoverflow.com/questions/8301947/…Amndeep7

5 Answers

74
votes
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}
128
votes

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

import scala.collection.JavaConverters._

def findAllQuestion():List[Question] = {
  questionDao.getAllQuestions().asScala.toList
}
32
votes
def findAllStudentTest(): List[StudentTest] = { 
  studentTestDao.getAllStudentTests().asScala.toList
} 
13
votes

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)
8
votes

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
}