Skip to main content

Open API without subclass opt-in

DiagnosticOPEN_API_WITHOUT_SUBCLASS_OPT_IN
Default severityError
Gradle propertyopenApiWithoutSubclassOptIn
Exemption@IntentionallyOpen

What it reports​

An open or abstract class in the public API with a constructor that external subclasses can call, or a non-sealed interface, without @SubclassOptInRequired.

public open class Component

Rationale​

A new abstract member or a changed member signature can break external subclasses. For an unstable subclass contract, use @SubclassOptInRequired.

Don't​

public interface Plugin {
public fun run()
}

Do​

@RequiresOptIn
public annotation class InternalMyLibrarySubclassApi
@SubclassOptInRequired(InternalMyLibrarySubclassApi::class)
public interface Plugin {
public fun run()
}

Notes​

  • Classes whose constructors are all internal or private aren't reported.

  • Users implement a fun interface with a lambda, so external implementations are its purpose. @SubclassOptInRequired isn't applicable to a fun interface, and the compiler rejects it. The check reports the fun interface anyway. The open contract must be an explicit decision of the author, so acknowledge the external implementations with @IntentionallyOpen.

    public fun interface Listener {
    public fun onEvent()
    }
    @IntentionallyOpen(reason = ExemptionReason.API_DESIGN)
    public fun interface AcknowledgedListener {
    public fun onEvent()
    }
  • In a multiplatform project, users on a platform can subclass the actual declaration. The check reports an actual declaration that is open when its expect declaration isn't:

    • An open actual class for a final expect class.
    • A public or protected constructor that only the actual class declares.
    • An actual typealias to an open class or interface of another module. @SubclassOptInRequired doesn't apply to a type alias, so declare an actual class or interface instead.
    • An actual typealias to an open Java class or interface of the module. Apply @SubclassOptInRequired to the Java declaration.

    @IntentionallyOpen on an expect declaration also exempts its actual declarations.

  • Subclass opt-in without markers reports a markerless @SubclassOptInRequired instead.

  • Exhaustive public API reports sealed types.

  • @PublishedApi internal types aren't reported.

Exemption​

If this is intended, apply @IntentionallyOpen to the class, interface, or type alias.

Use the exemption when the declaration is part of the API design or must stay for backwards compatibility.

@IntentionallyOpen(reason = ExemptionReason.API_DESIGN)
public open class Widget

Configuration​

build.gradle.kts
apiWatchdog {
openApiWithoutSubclassOptIn = WatchdogSeverity.ERROR
}

For a direct compiler call:

-P plugin:org.jetbrains.kotlinx.library.api.watchdog:diagnosticSeverity=OPEN_API_WITHOUT_SUBCLASS_OPT_IN:error

See also​