Skip to content

Scope implements AutoCloseable#2363

Open
lidonis wants to merge 1 commit into
InsertKoinIO:4.2.0from
lidonis:scope-autocloseable
Open

Scope implements AutoCloseable#2363
lidonis wants to merge 1 commit into
InsertKoinIO:4.2.0from
lidonis:scope-autocloseable

Conversation

@lidonis
Copy link
Copy Markdown
Contributor

@lidonis lidonis commented Feb 9, 2026

Summary

  • Scope now implements AutoCloseable, enabling Kotlin's use { } pattern for safe scope lifecycle management
  • close() already existed with the right signature, so the only change is adding the interface declaration and override modifier
  • This is a source-compatible and binary-compatible change with no behavioral differences

Motivation

Koin's Scope has a close() method but doesn't implement AutoCloseable. This means developers can't use Kotlin's use { } pattern and must rely on manual try/finally blocks, which is error-prone.

With this change:

koin.createScope<MyScope>().use { scope ->
    scope.get<MyService>().execute()
}
// scope.close() called automatically, even on exceptions

This is the same pattern Kotlin developers use for InputStream, Connection, ResultSet, etc. Scopes hold resources and have a lifecycle, so they belong in this family.

Changes

  • Scope.kt: Added AutoCloseable interface and override on close()
  • ScopeAPITest.kt: Two new tests verifying use { } works and closes on exceptions
  • scopes.md: Updated documentation with use { } as the recommended approach for short-lived scopes

Compatibility

  • Source compatible: existing code compiles without changes
  • Binary compatible: adding an interface is ABI-safe
  • Behavioral: no change, close() already exists with identical semantics
  • Multiplatform: AutoCloseable is available in kotlin.stdlib for all targets since Kotlin 1.8

Test plan

  • scope implements AutoCloseable and works with use verifies use { } resolves instances and auto-closes
  • scope use closes on exception verifies close is called even when an exception is thrown
  • All existing ScopeAPITest tests pass (13/13)

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.
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