簡體   English   中英

如果嘗試在視圖類中將值放入映射中,為什么會出現錯誤?

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

我試圖將值添加到scala類中的地圖。

我在控制器類中有一個帶有question / answerList對的通用映射:

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)); 
}

在我的視圖類中,我向地圖添加了一個新的問題/答案對:

@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]);
}

但是,當我運行代碼時,錯誤頁面出現,並說:“特征列表是抽象的;無法實例化”。 為什么我不能在地圖中放入(問題,列表[答案])對?

收到錯誤是因為,正如錯誤消息所指出的那樣:您無法實例化抽象類。

您需要實例化它的子類。

new List[Answer]

將永遠無法工作。 實例化一個適合您需求的子類。

正如StultuskeKulu Limpa指出的,您需要實例化一個子類。 這將起作用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM