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

前端 未结 5 811
野的像风
野的像风 2020-12-02 08:01

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

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


        
相关标签:
5条回答
  • 2020-12-02 08:46

    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)
    
    0 讨论(0)
  • 2020-12-02 08:47
    def findAllStudentTest(): List[StudentTest] = { 
      studentTestDao.getAllStudentTests().asScala.toList
    } 
    
    0 讨论(0)
  • 2020-12-02 08:55

    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
    }
    
    0 讨论(0)
  • 2020-12-02 08:56

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

    import scala.collection.JavaConverters._
    
    def findAllQuestion():List[Question] = {
      questionDao.getAllQuestions().asScala
    }
    
    0 讨论(0)
  • 2020-12-02 08:59
    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}
    
    0 讨论(0)
提交回复
热议问题