foreach
문에서 패턴 일치 후 아무 것도 할 수 있습니까?
게시물 일치 단계를 수행하고 싶습니다. 예 : 변수를 설정합니다. 또한 foreach
이 String => Unit이므로 Unit 반환을 원합니다. 기본적으로 Scala는 마지막 명령문을 반환하려고합니다. 업데이트]foreach에서 패턴 일치를 수행 한 다음 마지막 단계를 수행하십시오
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)
)
: 새로운 코드와 컨텍스트 여기
몇 가지 코드입니다. 또한 새로운 질문이 추가되었습니다. :) 주석에 포함되어 있습니다.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)
}
더 쉽게 할 수 있습니다. 'xs foreach {case "date"=> ....}' – tilex