I think what’s confusing is that while many of the words are familiar to you — object, class… — some of the ideas they represent may be subtly different from what you’re used to.
(At least, so I gather — I don’t know JavaScript, so I have the opposite problem!)
Anyway, let me try to explain a few relevant things, in case it helps…
In Kotlin, everything is an object. And each object is an instance of some class. In most cases, it’s a named class — for example, "ABCDE"
is an instance of the class String
. And (most) named classes can have many different instances.
You define a class with the class
keyword, e.g.:
class MyClass(var myField: Int) {
// …
}
(It’s conventional to start class names with a capital letter, and function/property/parameter/variable names with a lower-class letter — you don’t have to, but it’s likely to stick out and confuse people if you don’t.)
So MyClass(1)
would create a new instance of your class, and you could store it in a variable (or pass it as a parameter) whose type was MyClass
.
Kotlin also allows for a special type of class which is a singleton, with only one instance. These are defined in the same way, except that they use the object
keyword instead of class
:
object MySingleton {
// …
}
You can refer to this instance simply as MySingleton
; but you can’t create any further instances. You could store it in a variable of type MySingleton
, but there wouldn’t be any point — that variable couldn’t refer to anything else except that one instance, so you might as well just refer to it directly.
(You could also store it in a variable of type Any
, which is the ultimate parent of all classes in Kotlin.)
Of course, this gets more complicated if you want your singleton object to extend another class, e.g.:
object MySingletonMyClass : MyClass(1) {
// …
}
Here the singleton is a subclass of MyClass
, so you could also store it in a variable of type MyClass
— and it could make sense to do so, since there could be other instances of MyClass
(or other subclasses) that it could refer to.
The third language feature which is relevant is an anonymous object. Suppose you want an extension of MyClass
, but you only want to use it in one place so you don’t want to create a named class for it. You can create a one-off subclass on-the-fly:
var someVar = object : MyClass(1) {
// …
}
This creates a variable which refers to an unnamed subclass of MyClass
. It’s created as needed, but because you haven’t given the class a name, you can’t refer to its type directly. (So the variable will be of type MyClass
, the nearest named type.)
In my experience, anonymous classes aren’t too common in Kotlin; they’re very handy when calling Java methods that expect you to provide an implementation of a Java interface or adapter, but in pure Kotlin such a method would be much more likely to take a function type that you can pass a lambda to instead.