boy*_*od3 102 scala list scala-java-interop
我有这个Scala方法,错误如下.无法转换为Scala列表.
def findAllQuestion():List[Question]={
questionDao.getAllQuestions()
}
Run Code Online (Sandbox Code Playgroud)
类型不匹配; 发现:java.util.List[com.aitrich.learnware.model.domain.entity.Question]必填:
scala.collection.immutable.List[com.aitrich.learnware.model.domain.entity.Question]
Fyn*_*ynn 111
您可以使用Scala简单地转换List JavaConverters:
import scala.collection.JavaConverters._
def findAllQuestion():List[Question] = {
questionDao.getAllQuestions().asScala
}
Run Code Online (Sandbox Code Playgroud)
Nei*_*eil 68
import scala.collection.JavaConversions._
Run Code Online (Sandbox Code Playgroud)
会为你做隐式转换; 例如:
var list = new java.util.ArrayList[Int](1,2,3)
list.foreach{println}
Run Code Online (Sandbox Code Playgroud)
boy*_*od3 27
def findAllStudentTest(): List[StudentTest] = {
studentTestDao.getAllStudentTests().asScala.toList
}
Run Code Online (Sandbox Code Playgroud)
Xav*_*hot 14
开始Scala 2.13,该包scala.collection.JavaConverters被标记为已弃用,以支持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)
Run Code Online (Sandbox Code Playgroud)
导入JavaConverters,@ fynn的响应丢失了toList
import scala.collection.JavaConverters._
def findAllQuestion():List[Question] = {
// java.util.List -> Buffer -> List
questionDao.getAllQuestions().asScala.toList
}
Run Code Online (Sandbox Code Playgroud)