我有以下 Controller 方法:
def edit(bookId: Int): Action[AnyContent] = messagesAction {implicit request => {
val books = Book.getBookId(bookId)
if(books.nonEmpty) Ok(views.html.book.create(bookForm.fill(books.head)))
else NotFound("Book is not found.")
}}
但我对自己的做法并不满意。
实际上,我不想测试列表(书籍 val)的空性。
我试过类似的东西:
def edit2(bookId: Int): Action[AnyContent] = messagesAction {implicit request => {
Book.getBookId(bookId).foreach(book => Ok(views.html.book.create(bookForm.fill(book))))
NotFound("Book is not found.")
}}
它确实可以编译,但我每次都有 NOtFound 重定向。
我怎么能这样做?
最佳答案
也许您只是在寻找模式匹配?
Book.getBookId(bookId) match {
//get head of list and ignore rest
case book :: _ => Ok(views.html.book.create(bookForm.fill(book)))
//if list is empty return not found
case Nil => NotFound("Book is not found.")
}
关于scala - 不在 Controller 的方法中使用 head on list,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56820344/