为什么我会得到一个 IndexOutOfBoundsException 而我的 else 应该阻止它?

Why do I get an IndexOutOfBoundsException when my else should prevent it?

我正在做某种测验并有一个问题和答案列表,这些问题和答案会通过控制器传输到我的视图 class。人们可以在页面上提问和回答问题,然后我的系统会 "collects" 那些人进行测验。

如果您是第一个开始程序/测验的人,则问题列表为空。因此我想检查一个带有 if / else 子句的空测验,if-case 似乎工作正常,但 else-case 抛出一个 IndexOutOfBoundsException 我不明白为什么。我认为当问题列表为空时不会使用 else-part,因此不应抛出异常。应该....

查看class:

@(questionList: List[Question], answerList: List[Answer], answerRadioForm: Form[Answer])

@if(questionList.length == 0){
    No questions yet!
}

else {
<!-- As only the highest ranked question gets put into the List, there is only one entry on first place -->
<b>@questionList.get(0).questionText</b>

    @for(question <- questionList)  {
        @question.questionText - @question.ownerID <br>
    }
} 

错误:

[IndexOutOfBoundsException: Index: 0, Size: 0]
49          <b>"""),_display_(/*27.8*/questionList/*27.20*/.get(0).questionText),format.raw/*27.40*/("""</b>

那么,我在这里缺少什么?

首先,您的代码是否可以编译,因为 List 上没有 get 方法。您可以改用 list.headOption

嗯,我可以用 questionList(0)

另一个解决方案。

@questionList.headOption.map(q => <b>{q.text}</b>).getOrElse("No questions yet!")
@for(question <- questionList)  {
    @question.text - @question.ownerId <br>
}

我找到了解决方案,尽管回答您自己的问题是一种不好的做法,但我为此搜索了几个小时,也许我的回答对其他人有帮助:

if / else 之间不能有 return / 换行符。

有效吗:

@if(questionList.length == 0){
    No questions yet!
}

else { ...

作品:

@if(questionList.length == 0){
    No questions yet!
} else {

编辑:由于 @if(questionList.length > 0){ 也能正常工作,可以稳定地防止意外插入换行符,并且更容易阅读和理解,所以我将使用它而不是其他的。