SingletonHolder

open class SingletonHolder<T, A>(creator: (A) -> T)

A base class for singletons that need one construction argument.

This is the multiplatform companion-object pattern for a singleton with an argument: the companion object of the singleton class extends this holder and callers obtain the instance through getInstance.

class Analytics private constructor(config: Config) {
companion object : SingletonHolder<Analytics, Config>(::Analytics)
}

val analytics = Analytics.getInstance(config)

The creator function runs on the first getInstance call and its reference is released afterwards; every later call returns the same instance and ignores its argument.

This class is not thread-safe.

Type Parameters

T

the singleton type.

A

the construction argument type.

Constructors

Link copied to clipboard
constructor(creator: (A) -> T)

Creates a holder that builds the instance with creator on first use.

Functions

Link copied to clipboard
fun getInstance(arg: A): T

Returns the singleton instance, creating it from arg on the first call. Later calls ignore arg and return the existing instance.