Scala Resource Safety
Resource safety is the guarantee that a resource is closed after use. The guarantee holds even when an error happens.
Using closes the resource after the block
The block uses the notebook and returns a result. The close marker prints after the block finishes.
import scala.util.Using
class Notebook(val name: String) extends AutoCloseable:
def write(line: String): Unit = println(name + " wrote " + line)
override def close(): Unit = println(name + " closed")
@main def main(): Unit =
val result = Using.resource(new Notebook("note")) { n =>
n.write("hello")
"done"
}
println(result)Using still closes the resource when the block throws
The block throws on purpose. The close marker prints before the catch case handles the problem.
import scala.util.Using
class Notebook(val name: String) extends AutoCloseable:
override def close(): Unit = println(name + " closed")
@main def main(): Unit =
try
Using.resource(new Notebook("note")) { n =>
throw new RuntimeException("boom")
}
catch
case e: RuntimeException => println("caught: " + e.getMessage)An inner resource closes before an outer one
Two resources nest inside each other. The inner close marker prints first.
import scala.util.Using
class Notebook(val name: String) extends AutoCloseable:
override def close(): Unit = println(name + " closed")
@main def main(): Unit =
Using.resource(new Notebook("outer")) { o =>
Using.resource(new Notebook("inner")) { i =>
println("both open")
}
}Example
import scala.util.Using
class Counter(val name: String) extends AutoCloseable:
var count = 0
def tick(): Unit =
count += 1
override def close(): Unit = println(name + " closed after " + count + " ticks")
@main def main(): Unit =
val total = Using.resource(new Counter("meter")) { m =>
m.tick()
m.tick()
m.tick()
m.count
}
println("total " + total)Key points
- Using resource: Using.resource runs a block with a resource and then closes it.
- Close marker: a close method that prints a marker makes the closing visible.
- Failure closing: the resource still closes when the block throws.
- Nesting order: an inner resource closes before an outer resource.
- In-memory model: this course models a resource with a small class, never with a real file.
In this example, Counter is an in-memory resource with a tick method and a close method. The block ticks three times and returns the count. Using.resource closes the counter before the total prints, so the close marker comes first.
Note
closing by hand can be skipped when an exception jumps past the close call.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does Using.resource guarantee?