Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add readWith method to StdIn #75

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/main/scala/scala/io/next/package.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/

package scala.io

package object next {
implicit class NextStdInExtensions(si: StdIn) {
/** Reads and applying a function on an entire line of the default input .
*
* @return the object A that was read
* @throws java.io.EOFException if the end of the
* input stream has been reached.
*/
def readWith[A](f: String => A): A = {
val s = si.readLine()
if (s == null)
throw new java.io.EOFException("Console has reached end of input")
else
f(s)
}
}
}
47 changes: 47 additions & 0 deletions src/test/scala/scala/io/TestStdInExtensions.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/

package scala.io

import next._

import org.junit.Assert._
import org.junit.Test

import java.io.ByteArrayInputStream
import java.io.InputStream

class TestStdInExtensions {
@Test
def readArray(): Unit = {
val in = new ByteArrayInputStream("1 2 3 4".getBytes)
Console.withIn(in) {
assertArrayEquals(
StdIn.readWith(input => input.split(" ").map(_.toInt)),
Array(1, 2, 3, 4))
}
}

@Test
def readClass(): Unit = {
case class Person(name: String, age: Int)
val in = new ByteArrayInputStream("John 34".getBytes)
Console.withIn(in) {
assertEquals(
StdIn.readWith(input => {
val Array(name, age) = input.split(" ")
Person(name, age.toInt)
}),
Person("John", 34))
}
}
}