Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized singleton in Kotlin

I am new to Kotlin. Still learning basic syntax. I've heard about companion objects similar to static in Java. But don't know how to create synchronized singleton in Kotlin.

like image 282
New Android Developer Avatar asked Sep 18 '25 07:09

New Android Developer


1 Answers

Just use

object Singleton {
    // any members you need
}

It's already synchronized properly:

Object declaration's initialization is thread-safe.

Note that this doesn't guarantee calls on it thread-safe, but that's just as in Java.

like image 169
Alexey Romanov Avatar answered Sep 20 '25 20:09

Alexey Romanov