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

时间:2013-04-23 06:04:19

标签: list scala scala-java-interop

我有这个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 个答案:

答案 0 :(得分:104)

您可以使用Scala的JavaConverters

简单地转换List
import scala.collection.JavaConverters._

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

答案 1 :(得分:65)

import scala.collection.JavaConversions._

将为您进行隐式转换; e.g:

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

答案 2 :(得分:26)

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

答案 3 :(得分:5)

导入JavaConverters,@ fynn的回复缺少toList

import scala.collection.JavaConverters._

def findAllQuestion():List[Question] = {
  //           java.util.List -> Buffer -> List
  questionDao.getAllQuestions().asScala.toList
}

答案 4 :(得分:1)

window.UserCollection = Backbone.PageableCollection.extend({ model: window.ShowUser, urlRoot: 'blah.com', state: { firstPage:1, pageSize:16 }, mode: "client", // page entirely on the client side }); window.CollectionView = Backbone.View.extend({ template: _.template($('#CollectionTemplate3').html()), initialize: function(options) { this.listenTo(this.eventAggregator, "showDifferentUser", this.resetTickBoxes); var columns = [ { name: '', //tickboxes have no name... label: 'Select', cell: Backgrid.BooleanCell.extend({ events : { 'change': function(ev){ var $checkbox = $(ev.target); var $checkboxes = $('.backgrid input[type=checkbox]'); // Disable all checkboxes but this one $checkboxes.attr("disabled", true); $checkbox.removeAttr("disabled"); // do more stuff here... } } }) }, { name: "id", // The key of the model attribute label: "ID", // The name to display in the header editable: false, // By default every cell in a column is editable cell: "string" }, { name: "last_name", label: "Surname", editable: false, // Display only! cell: "string" // This is converted to "StringCell" and a corresponding class in the Backgrid package namespace is looked up }]; <more code here> // instantiate collection var userCollection = new window.UserCollection; // Set up a grid view to use the pageable collection var userGrid = new Backgrid.Grid({ columns: columns, collection: userCollection }); // Initialize the paginator var paginator = new Backgrid.Extension.Paginator({ collection: userCollection }); 开始,软件包Scala 2.13被标记为不赞成使用scala.collection.JavaConverters

scala.jdk.CollectionConverters