9.8 Closeables
The Closeable.let definition form binds a name to a Closeable object and injects a call to its close method to close the object after subsequent definitions and expressions. Implementing the Closeable interface allows an object to cooperate with Closeable.let.
definition | |||
|
The rhs_expr is evaluated with breaks disabled like the ~initially part of try. If control escapes from the body sequence (e.g., because an exception is raised), then the object produced by rhs_expr is closed before escaping, and breaks are disabled during that close as in the ~finally part of try. Consequently, in the case of a break exception, the object is reliably closed or not yet opened by rhs_expr. A continuation jump back into the body sequence is disallowed via Continuation.barrier.
> block:
Closeable.let i = Port.Input.open_file("data.txt")
i.read_line()
// `i` is closed after this point
"file content"
The Closeable interface has one method:
close() —
closes the object. Closing an already-closed object should succeed without any effect. The result should normally be #void, but the result is not specifically constrained by the Closeable interface.