I saw some code that defines a function-local `obj...
# getting-started
y
I saw some code that defines a function-local
object
that captures a local variable that's basically a
class
, right? there's no benefit to making it an
object
?
e
an
object
is an instance of some class (named or not), and you need an instance to capture
e.g.
Copy code
fun f(name: String): Any {
    return object {
        override fun toString(): String = name
    }
}
is roughly equivalent to
Copy code
fun f(name: String): Any {
    class `f$1` {
        override fun toString(): String = name
    }
    return `f$1`()
}
y
ah, I see. so an
object
is just a class instance that also has the property of being a singleton?
e
an
object
expression is not a singleton
y
okay now I see. thanks.
s
| an
object
expression is not a singleton but doesn't create an object expression a singleton of an anonymous class?? Your second link literally says "which is useful for implementing singletons"
e
it can be but it is not a singleton itself
Copy code
fun f() = object {}
f() != f()
f()::class == f()::class
👍 2
s
but surprisingly
Copy code
f()::class !== f()::class
so the classes are equivalent, but not identical. And if the classes are not identical than you could
f()
still call a singleton 🤔 here is the code: https://pl.kotl.in/w35NYuhj9
y
I think
::class
doesn't work that way. for example,
String::class !== String::class
👍 1
looks like it's a property of the instance