Skip to content

Scope implements AutoCloseable - #2493

Open
lidonis wants to merge 3 commits into
InsertKoinIO:4.3.0from
lidonis:scope-autocloseable-4.3-pr
Open

lidonis wants to merge 3 commits into
InsertKoinIO:4.3.0from
lidonis:scope-autocloseable-4.3-pr

Conversation

@lidonis

@lidonis lidonis commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

What & why

Scope already has a close(); implementing AutoCloseable lets a short-lived scope be closed with use { }, even when the block throws:

koin.createScope<RequestScope>().use { scope ->
    scope.get<Handler>().handle()
}

Follows #2363 (same change on 4.2.0, closed by the stale bot without review), rebased onto 4.3.0. Companion of #2491, which does the same for Koin and KoinApplication.

Public API

  • ./gradlew apiCheck passes
  • Additions only, .api dump regenerated: Scope gains java/lang/AutoCloseable, and close() loses final in the dump. Scope is a final class, so nothing can override it. Source and binary compatible.
  • No removals or signature changes

Behavior change

None. close() is unchanged; it is now also reachable through AutoCloseable.

Tests

  • New behavior, in ScopeAPITest (commonTest): use { } closes the scope; use { } closes it when the block throws and rethrows the original exception; close() after use { } does not throw.

Verified beyond the JVM (for commonMain changes)

  • :core:koin-core:jvmTest (324 tests, 0 failures), :core:koin-core:macosArm64Test (ScopeAPITest 14/14) and :core:koin-core:compileKotlinWasmJs pass.

Docs

  • docs/reference/koin-core/scopes.md: use { } for short-lived scopes, and a note to use it only on a scope you created, not on one returned by getScope or owned by a lifecycle (activityScope()).

🤖 Generated with Claude Code

lidonis and others added 3 commits November 9, 2026 14:32
Enables Kotlin's `use { }` pattern on Scope, guaranteeing cleanup
even on exceptions. This is a source-compatible and binary-compatible
change close() already existed with the right signature.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant