Something that’s always stumped me. Why do anonymo...
# announcements
s
Something that’s always stumped me. Why do anonymous inner classes in Kotlin start with
object
? That seems to be a misnomer to me, and that it should be
class
instead. What am I missing?
z
You can’t create an anonymous class without creating an instance of it at the same time. So you’re really creating a new object, whose class happens to be anonymous.
s
but object implies it’s a singleton
z
Does it? I think of it the other way around –
object
creates an instance. If that object is top-level, then it’s a singleton.
👍 4
s
Yup,
object
does not always imply a singleton.
Copy code
fun test() {
    val callback = object : Callback<Int> {
        override fun onSuccess(value: Int) { ... }
    }
    ...
}
👍 1
s
@streetsofboston That’s what I’m saying though. In Kotlin, the difference between an object and a class is that one is a singleton. In your example, that’s not compiled to a singleton (in some cases it can be actually, i.e. if you don’t access the parent scope). Isn’t
object
a misnomer there?
s
If you define a singleton as the one and only possible value of a particular Type/Class, then yes, all `object`s are singletons and all `companion object`s are singleton (Type contains exactly one value). In my example, the
callback
variable has an anonymous type, whose base-class is
Callback<Int>
and this type’s one and only value is held by
callback
j
objects are instances of anonymous classes. You can just as easily declare a named class to do the same thing. But I'm a lazy programmer and I don't want to type letters or worry about some other silly programmer using my class in a way that's undesirable. It's meant for this one thing in this one spot in my program.
s
Agree with zach here
object
feels more like an instance also you can create an anonymous object without extending anything
Copy code
val a = object {
   val b: Int = 0
}
println(a.b)
In that regard, named
object
feels like just a handy way of doing the above for top level without creating variables.
c
I like to think of top-level and companion objects as “objects with names”. An object is just some generic instance of a thing, but being able to refer to it by name is what makes it unique
☝️ 1
a
i'm really new to K but...
Copy code
val a = object {
   val b: Int = 0
}
println(a.b)
for this example, is the
object
keyword required? why not
Copy code
val a = {
   val b: Int = 0
}
println(a.b)
j
@alex j did you compile those? My eyeball compiler thinks that in the second example
a
is assigned to an anonymous function where
b
is a local variable, which is entirely different than the first example.
a
ok that makes sense. so with the second example, is
println(a.b)
even a legal statement?
j
I don't think so
✔️ 1