When returning a new instance of an anonymous clas...
# getting-started
k
When returning a new instance of an anonymous class, in Java it's obvious that it's a new instance:
Copy code
return new InterfaceXXX() {
    @Override public void foo() {}
    @Override public void bar() {}
}
But Kotlin uses the
object
keyword:
Copy code
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?
🚫 1
j
It never bothered me to be frank. Just like writing
val 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)
👍🏾 1
👍 2
s
I don’t think I find the Kotlin version particularly more or less confusing than the Java version. In both cases it’s the place where it’s declared that lets me know the scope/lifecycle, not the syntax.
👍🏾 1
👍 2
e
you can't tell from a visual inspection whether
Person("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 instances
👆 2
j
@ephemient true, although I have a pretty detailed color theme that helps me distinguish some of those cases visually
🌈 1