https://kotlinlang.org logo
Title
p

pankajrai

04/23/2018, 12:02 PM
Do creation of Singleton has been changed now? object MySingleton { val num:Int = 10 } No longer create a private constructor
a

andyb

04/23/2018, 12:08 PM
Yep, that is correct
p

petersommerhoff

04/23/2018, 12:46 PM
Why this change?
a

andyb

04/23/2018, 12:49 PM
It's an explicit implementation of
Item 3: Enforce the singleton property with a private constructor or an enum type
from Joshua Bloch's Effective Java book. It makes it impossible for the developer to f***-up the definition of a Singleton
It uses the same approach of Singletons & Companion Objects as Scala😒cala:
p

petersommerhoff

04/23/2018, 12:51 PM
I think I misunderstood...I thought there was now a non-private constructor but still is private when trying to call from Java
a

andyb

04/23/2018, 12:52 PM
It's a change coming from Java but this approach has been in Kotlin since before 1.0
Yep, if you have a look at the generated byte code it is still implemented as a private constructor
p

petersommerhoff

04/23/2018, 1:08 PM
I know, I was confused because I don't see a private constructor in the decompiled Java code...but in the bytecode it's there, you're right