Skip to content

Instantly share code, notes, and snippets.

@TheDIM47
Last active August 29, 2015 14:22
Show Gist options
  • Save TheDIM47/412a9312295edb883598 to your computer and use it in GitHub Desktop.
Save TheDIM47/412a9312295edb883598 to your computer and use it in GitHub Desktop.
Simple Scala console app which handles user's input asynchronously
package user.demo
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
/**
* Scala console app which handles user's input asynchronously.
* Each user answer should be set to default value by timeout.
*/
object DemoApp extends App {
@volatile var terminated = false
val questions = ("What is your name?", "John Doe") ::("What is your age?", 20) ::("Where are you from?", "USA") :: Nil
val answers = for (q <- questions) yield {
terminated = false
println(q._1)
val f = Future {
var buf: List[Char] = Nil
while (!terminated) {
if (Console.in.ready()) {
val ch = Console.in.read()
if (ch.toChar == 10) terminated = true
else buf = ch.toChar :: buf
}
}
buf.reverse.mkString
}
try {
Await.result(f, 5.seconds)
} catch {
case _ =>
terminated = true
q._2
}
}
answers foreach println
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment