Last active
August 29, 2015 14:22
-
-
Save TheDIM47/412a9312295edb883598 to your computer and use it in GitHub Desktop.
Simple Scala console app which handles user's input asynchronously
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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