首页 文章

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

提问于
浏览
89

我有这个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]

5 回答

  • 63
    def findAllStudentTest(): List[StudentTest] = { 
      studentTestDao.getAllStudentTests().asScala.toList
    }
    
  • 100

    导入 JavaConverters ,@ fynn的回复丢失 toList

    import scala.collection.JavaConverters._
    
    def findAllQuestion():List[Question] = {
      //           java.util.List -> Buffer -> List
      questionDao.getAllQuestions().asScala.toList
    }
    
  • 0

    Scala 2.13 开始,包 scala.collection.JavaConverters 被标记为已弃用,有利于 scala.jdk.CollectionConverters

    import scala.jdk.CollectionConverters.Ops._
    
    // val javaList: java.util.List[Int] = java.util.Arrays.asList(1, 2, 3)
    javaList.asScala.toList
    // List[Int] = List(1, 2, 3)
    
  • 25

    您可以使用Scala的 JavaConverters 简单地转换List:

    import scala.collection.JavaConverters._
    
    def findAllQuestion():List[Question] = {
      questionDao.getAllQuestions().asScala
    }
    
  • 5
    import scala.collection.JavaConversions._
    

    会为你做隐式转换;例如 . :

    var list = new java.util.ArrayList[Int](1,2,3)
    list.foreach{println}
    

相关问题