Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scala 3 Using – problems when reading from file

In a Scala 3 project, I have a method which returns a Try from a given String

def translate(text: String) : Try[Thing] = ...

and a method which is supposed to read the contents of a file and pass it on to the first method. Here, I want to use Using because as far as I understand, this is the functional way to handle file I/O, and it returns a Try which I need anyway, and it makes sure the used resource is closed:

  def translateFromFile(filepath: String) : Try[Thing] =
    Using(Source.fromFile(filepath).getLines.mkString) match
      case Success(s) => translate(s)
      case Failure(e) => Failure(e)

However, the compiler says

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

given instance of type scala.util.Using.Releasable[String] was found for parameter evidence$1 of method apply in object Using

Honestly, I don’t understand this error message, and I couldn’t find any help online. Can someone help? What’s the correct way to do this? Thanks!

>Solution :

The error means that you’re trying to substitute into Using(...) not something that can be closed but a String.

It should be

def translateFromFile(filepath: String) : Try[Thing] =
  Using(Source.fromFile(filepath)) { s =>
    translate(s.getLines.mkString) match {
      case Success(s) => ???
      case Failure(e) => ???
    }
  }

or just

def translateFromFile(filepath: String) : Try[Thing] =
  Using(Source.fromFile(filepath)) { s =>
    translate(s.getLines.mkString)
  }.flatten

Using(...){s => ...} returns Try and your translate returns Try, so it’s Try[Try[...]], that’s why .flatten.

There is nothing specific to Scala 3.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading