Skip to content

[feature]: Change chained Scope release order from FIFO to LIFO. #1439

@megri

Description

@megri

Problem Statement

Chains of Scope.acquire are released in the order they are acquired, so the first acquired resource will be released first. This feels unintuitive and goes against most conventions I've found elsewhere; Java's try-with-resources for instance is explicitly documented to release resources in reverse order of acquisition. Having the current behaviour can lead to nasty bugs, but if the design is intentional I think it should at least be documented.

Proposed Solution

Change release order from FIFO to LIFO.

Alternative Solutions

No response

Current Workaround

You can work around the limitation by explicitly wrapping nested scopes in Scope.run. So from my understanding something like

for
    in <- Scope.acquire(FileInputStream("foo.zip"))
    gzip <- Scope.acquire(GZIPInputStream(in))
    reader <- Scope.acquire(InputStreamReader(gzip, "UTF-8"))
yield process(reader)
…

could be rewritten to work as indended as

for
    in <- Scope.acquire(FileInputStream("foo.zip"))
    result1 <- Scope.run(
        for
            gzip <- Scope.acquire(GZIPInputStream(in))
            result2 <- Scope.run(
                for
                    reader <- Scope.acquire(InputStreamReader(gzip, "UTF-8"))
                yield
                    process(reader)
            )
        yield result2
    )
yield result1

but it's not pretty.

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions