在foreach模式匹配然后做最后一步

Far*_*mor 5 scala playframework playframework-2.0

foreach语句中匹配模式后是否可以执行任何操作?
我想做一个匹配后步骤,例如设置一个变量.我也想强制一个Unit返回,因为我的foreach是String => Unit,默认情况下Scala想要返回最后一个语句.

这是一些代码:

    Iteratee.foreach[String](_ match {
      case "date" => out.push("Current date: " + new Date().toString + "<br/>")
      case "since" => out.push("Last command executed: " + (ctm - last) + "ms before now<br/>")
      case unknow => out.push("Command: " + unknown + " not recognized <br/>")
    } // here I would like to set "last = ctm" (will be a Long) 
    ) 
Run Code Online (Sandbox Code Playgroud)

更新: 新代码和上下文.还添加了新问题:)它们嵌入在评论中.

def socket = WebSocket.using[String] { request =>

 // Comment from an answer bellow but what are the side effects?
 // By convention, methods with side effects takes an empty argument list
 def ctm(): Long = System.currentTimeMillis

 var last: Long = ctm

 // Command handlers
 // Comment from an answer bellow but what are the side effects?
 // By convention, methods with side effects takes an empty argument list
 def date() = "Current date: " + new Date().toString + "<br/>"
 def since(last: Long) = "Last command executed: " + (ctm - last) + "ms before now<br/>"
 def unknown(cmd: String) = "Command: " + cmd + " not recognized <br/>"

 val out = Enumerator.imperative[String] {}

 // How to transform into the mapping strategy given in lpaul7's nice answer.
 lazy val in = Iteratee.foreach[String](_ match {
   case "date" => out.push(date)
   case "since" => out.push(since(last))
   case unknown => out.push(unknown)
 } // Here I want to update the variable last to "last = ctm"
 ).mapDone { _ =>
   println("Disconnected")
 }

 (in, out)
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*Hsu 14

我不知道你ctm是什么,但你总能做到这一点:

val xs = List("date", "since", "other1", "other2")

xs.foreach { str =>

    str match {
        case "date"  => println("Match Date")
        case "since" => println("Match Since")
        case unknow  => println("Others")
    } 

    println("Put your post step here")
}
Run Code Online (Sandbox Code Playgroud)

请注意,您应该使用{}而不是()在您希望使用一段代码作为foreach()的参数时使用.