We'd like to have a single instance of a class that will be used throughout our codebase. We created a dedicated package to hold this instance. If I understand it right, there are two ways to declare a singleton.
(The examples use Jackson but this is not specific to it in any way.)
Object
package net.goout.jackson
import com.fasterxml.jackson.databind.ObjectMapper
...
object Jackson : ObjectMapper() {
init {
configure(...)
}
}
File-level val
package net.goout.jackson
import com.fasterxml.jackson.databind.ObjectMapper
...
val jackson = ObjectMapper().apply {
configure(...)
}
In both cases only one instance is ever created and the call sites are identical (apart from the slight difference in the naming).
Is there any practical difference between the two approaches?