Skip to content

Koin and KoinApplication implement AutoCloseable#2374

Open
lidonis wants to merge 1 commit intoInsertKoinIO:4.2.0from
lidonis:koin-koinapplication-autocloseable
Open

Koin and KoinApplication implement AutoCloseable#2374
lidonis wants to merge 1 commit intoInsertKoinIO:4.2.0from
lidonis:koin-koinapplication-autocloseable

Conversation

@lidonis
Copy link
Copy Markdown
Contributor

@lidonis lidonis commented Mar 6, 2026

Summary

  • Koin and KoinApplication now implement AutoCloseable, enabling Kotlin's use { } pattern for safe resource cleanup
  • close() already existed with the right signature on both classes, 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 Koin and KoinApplication have close() methods but don'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:

koinApplication {
    modules(myModule)
}.use { app ->
    val service: MyService = app.koin.get()
    // work with service
}
// app.close() called automatically, even on exceptions

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

This is a companion to #2363, which added AutoCloseable to Scope.

Changes

  • Koin.kt: Added AutoCloseable interface and override on close()
  • KoinApplication.kt: Added AutoCloseable interface and override on close()
  • KoinAutoCloseableTest.kt: Four tests verifying use { } works and closes on exceptions for both classes
  • start-koin.md / starting-koin.md: Updated documentation with use { } examples

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

  • Koin implements AutoCloseable and works with use verifies use { } resolves instances and auto-closes
  • Koin use closes on exception verifies close is called even when an exception is thrown
  • KoinApplication implements AutoCloseable and works with use verifies use { } resolves instances and auto-closes
  • KoinApplication use closes on exception verifies close is called even when an exception is thrown

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