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

Consider a Sink to mirror Source #144

Open
ekrich opened this issue Jan 12, 2023 · 2 comments
Open

Consider a Sink to mirror Source #144

ekrich opened this issue Jan 12, 2023 · 2 comments

Comments

@ekrich
Copy link

ekrich commented Jan 12, 2023

I know we are not wanting a big Scala library and such but this is where we could make some things easier for beginners or just for easy scripting. I was just doing some analysis on the sbt build for Scala Native and wrote the following. I think we could have something even easier than Python.

import scala.io.Source

val lines = Source
  .fromFile("config.txt")
  .getLines
  .toList
  .sorted
  .groupMapReduce[String, Int](identity)(_ => 1)(_ + _)
  .toList
  .map(t => t._1 + t._2)
  .sorted

val file = new java.io.FileWriter("config-out.txt")
for (line <- lines) file.write(line + "\n")
file.close()
@BalmungSan
Copy link
Contributor

BalmungSan commented Jan 13, 2023

For the record, I think of an API like:

def writeToFile[A](path: Path, contents: IterableOnce[A])(formatLine: A => String): Try[Unit]

Maybe, even something like Sink to complement Source

trait Sink extends AutoClosable {
  def write(str: String): Unit

  final def writeLine(str:): Unit = {
    write(str)
    write(System.lineSeparator)
  }

  final def writeAllFormat[A](data: IterableOnce[A])(formatLine: A => String): Unit = {
    data.foreach(a => writeLine(formatLine(a)))
  }

  /** Uses toString */
  final def writeAll[A](data: IterableOnce[A]): Unit = {
    wrtieAllFormat(data)(_.toString)
  }

  def close(): Unit
}

object Sink {
  def fromFile(path: Path): Sink
}

Which then could be used with Using.

@SethTisue
Copy link
Member

SethTisue commented Jan 24, 2023

There's os-lib, which has been selected for the Scala Toolkit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants