Question

How do I continue reading stdin until "END" string reached, in Scala?

Here's what I've tried:

val text = Iterator.continually(Console.readLine).takeWhile(_ != "END").toString
Was it helpful?

Solution

You should use mkString instead of toString here:

val text = Iterator.
    continually(Console.readLine).
    takeWhile(_ != "END").
    mkString("\n")

mkString on collection aggregates all elements in a string using optional separator.

OTHER TIPS

You can use simple recursion function like this:

def r(s: String = ""): String = {
  val l = readLine
  if (l == "END") s
  else r(s + l)
}

You can call it r("") it return result string

Conole.readLine is deprecated. Use io.StdIn.readLine instead. Here a complete program with your code fragment. The only change I made is that it reads the entire input, until the user presses Ctrl-D or EOF is encountered:

import io.StdIn.readLine

object Reader extends App {
  val x = Iterator
    .continually(readLine)
    .takeWhile(_ != null)
    .mkString("\n")
  println(s"STDIN was: $x")
}

I guess you want something like this:

var buffer = ""
Iterator.continually(Console.readLine).takeWhile(_ != "END").foreach(buffer += _)
val text = buffer
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top