Search code examples
scalafunctioninputstream

Handling InputStream in Scala


I have a method that takes inputStream as a parameter. An InputStream, which contains the following

  • input:

  • A line containing a single number: N

  • Followed by N lines containing two numbers Ti and Li separated by space.

  • There may be a trailing newline.

The question is: How do I read and manipulate the stream in scala?

def process(in: InputStream): Long = ???

Solution

  • Following code sample read n from the first line then for each line calculate multiplication of ti * li and total sum.

    import java.io.InputStream
    import java.io.ByteArrayInputStream
    import java.nio.charset.StandardCharsets
    
    import scala.io.Source
    import scala.util.matching.Regex
    
      def process(in: InputStream): Long = {
        val lines = Source.fromInputStream(in).getLines()
        val n = lines.next().toInt
        val pattern: Regex = """\s*(\d+)\s+(\d+)\s*""".r
        lines.map {
          case pattern(ti, li) => ti.toInt * li.toInt
          case _ => 0
        }.sum
      }
    
      test("process InputStream") {
        val lines =
          raw"""3
               |1 10
               |2 200
               |3 3000
               |""".stripMargin
        println(lines)
        val is: InputStream = new ByteArrayInputStream(lines.getBytes(StandardCharsets.UTF_8))
    
        assert(process(is) == 9410)
      }