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

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.

Leave a Reply