2015-05-08 100 views
1

我的微弱Scala技能讓我對正確的做事感到困惑。下面的代碼僅在包含t match {...行時編譯(並且工作)。如果我消除了這一行,當然還有前面一行的診斷println,我得到的編譯時錯誤如圖所示。顯然編譯器認爲fold的返回值是Unit(對我來說是驚喜)。這可能是合理的,但我不明白。有人會請我提供一個更好的代碼編寫方法,也許能給我更多的見解嗎?返回類型bindFromRequest.fold

[error] /home/bill/activator/cherry/app/controllers/Application.scala:34: type mismatch; 
[error] found : Unit 
[error] required: play.api.mvc.Result 
[error] } 
[error] ^

來源:

def ptweets = Action { implicit request => 
    import play.api.data._ 
    val rqForm = Form(Forms.mapping(
     "k" -> Forms.number, 
     "who" -> Forms.text, 
     "what" -> Forms.text)(TweetInquiry.apply)(TweetInquiry.unapply)) 
    val t = rqForm.bindFromRequest.fold(
     formWithErrors => BadRequest("That's not good"), 
     rq => Ok((views.html.properForm("POST tweets TBD.")(Html("<em>Blah</em>")))) 
    ) // expect a play.api.mvc.Result 
    println(t.getClass.getName) // this confirms it in both run-time cases 
    t match { case v:Result => v } // yet this is required for compile 
    } 
+0

將賦值移除到val? –

回答

4

爲MZ在評論中說,更改

val t = rqForm.bindFromRequest.fold(
     formWithErrors => BadRequest("That's not good"), 
     rq => Ok((views.html.properForm("POST tweets TBD.")(Html("<em>Blah</em>")))) 
    ) // expect a play.api.mvc.Result 
    println(t.getClass.getName) // this confirms it in both run-time cases 
    t match { case v:Result => v } // yet this is required for compile 

只是:

rqForm.bindFromRequest.fold(
     formWithErrors => BadRequest("That's not good"), 
     rq => Ok((views.html.properForm("POST tweets TBD.")(Html("<em>Blah</em>")))) 
    ) 

摺疊正在評估的結果,但在您發佈的代碼中,您正在分配該R成爲價值t。因此,不是評估摺疊結果的操作塊,而是評估一個分配(單元,見here)。