2015-05-08 64 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)。