如果我尝试将值放入视图 class 中的地图中,为什么会出现错误?

Why do I get an error if I try to put values into a map in my view class?

我正在尝试将值附加到 Scala 中的地图 class。

我的控制器中有一个带有问题/答案列表对的通用地图 class:

static Map<Question, List<Answer>> myMap = new HashMap<Question, List<Answer>>();

Question question1 = new Question("xyz", "Do Androids dream?", 127, "Marcus");
Answer answer11 = new Answer("zab", "xyz", "Only of electric sheep!", 70, "Sarah");

List<Answer> answerList1 = new ArrayList<Answer>();
answerList1.add(answer11);

// puts the question and its answers into the hashmap
myMap.put(question1, answerList1);

public static Result askQuestion(){
return ok(views.html.questionAnswer.render(myMap)); 
}

在我看来class我在地图中添加了一个新的问题/答案对:

@import model.Question
@import model.Answer

@(myMap: Map[Question, List[Answer]])

@main("Ask question"){
@myMap.put(new Question("id123", "questiontext", 34, "userID"), new List[Answer]);
}

但是当我 运行 代码时,错误页面出现,说:"trait List is abstract; cannot be instantiated"。为什么我不能将 (question, List[answer]) 对放入我的地图中?

您收到错误是因为,正如您的错误消息所述:您无法实例化抽象 class。

您需要实例化它的子class。

new List[Answer]

永远行不通。实例化一个适合您需要的子class。

正如Stultuske and Kulu Limpa所指出的,您需要实例化一个子类。这将起作用:

// Note: You need to tell the compiler which type Nill should use
@myMap.put(new Question("id123", "questiontext", 34, "userID"), Nil: List[Answer]);