1

I would like to know if there is a functional approach in identifying no lines are left to be read in the while condition when reading from, e.g. standard input or a file.

I have tried the Option/Some/None pattern in several ways, but nothing seems to work better than the old Java null with != boolean comparison operation.

var a: String = null.asInstanceOf[String]
while( { a = scala.io.StdIn.readLine; a != null } ) {
namesMap.get( a ) match {
    case Some( value ) => println( s"$a=$value" )
    case None => println( "Not found" )
  }
}

Can you please give some advice you can have as experienced Scala programmers?

Thanks in advance.

SCouto
  • 7,808
  • 5
  • 32
  • 49
  • Perhaps it's my TERM settings. In the REPL I can't get `io.StdIn.readLine` to return `null`. – jwvh Aug 27 '19 at 06:26

2 Answers2

1

How about this?

scala.io.Source.fromInputStream(System.in, "UTF-8").getLines().foreach { line =>
    println(namesMap.get( line ).map(value => s"$line=$value" ).getOrElse("Not Found"))
}
Thilo
  • 257,207
  • 101
  • 511
  • 656
1

If null is the only terminal condition, and println is the only result output:

Iterator.continually(Option(io.StdIn.readLine))
        .takeWhile(_.nonEmpty)
        .map(k => namesMap.get(k.get).fold("not found")(v => s"${k.get}=$v"))
        .foreach(println)

k.get is safe because it's been established that it is nonEmpty (i.e. not None).

jwvh
  • 50,871
  • 7
  • 38
  • 64