Klitos Kyriacou
09/09/2022, 8:09 AMreturn new InterfaceXXX() {
@Override public void foo() {}
@Override public void bar() {}
}
But Kotlin uses the object
keyword:
return object : InterfaceXXX {
override fun foo() {}
override fun bar() {}
}
And because it uses the object
keyword, it looks as if you are returning the same singleton instance every time. I have to do a double-take to notice it's not actually a singleton. Does this confuse others too?Joffrey
09/09/2022, 8:14 AMval p = Person("Bob")
at the top level gives me one single instance, while writing the same line in a function body gives me a different one everytime I call the function.
The term object
doesn't mean singleton in my mind, it just means an instance, like in Java. The fact that you can name an object and declare it like a class is a cool Kotlin feature, but it only means singleton at the top level (at least that's how I read it)Sam
09/09/2022, 8:15 AMephemient
09/09/2022, 9:22 AMPerson("Bob")
creates a new instance either - maybe it's a constructor, or maybe it's an value class, or maybe it's a constructor-like function that returns cached instancesJoffrey
09/09/2022, 10:20 AM