Reputation: 35
What does it mean by Everything is an object in Kotlin?
In Kotlin, everything is an object in the sense that you can call member functions and properties on any variable. Some types can have a special internal representation – for example, numbers, characters and booleans can be represented as primitive values at runtime – but to the user they look like ordinary classes
Upvotes: 0
Views: 391
Reputation: 70387
One of the very common criticisms of Java is that certain types, the primitive types, are treated specially. That is, there's a fundamental difference between int
and String
in Java. int
is primitive and String
is an object type. This has several downstream consequences.
int
is always passed by value, whereas String
is passed by reference.int
cannot be used in generics.int
is non-nullable, whereas String
can be null
.int
.int
doesn't derive from Object
, so even otherwise "universal" things like toString
won't work on it.So a Java programmer always has to be conscious of this and must treat these primitive types, in some sense, differently.
Kotlin eliminates this discrepancy. In Kotlin, Int
is a class type just like String
. It has methods, it's passed by reference, it can be nullable (Int?
is well-defined in Kotlin), and it derives from the top type Any
.
Internally, Kotlin is free to optimize this to a primitive int
to make your code faster. But crucially that's an implementation detail. You as the programmer are free to just assume everything is an object, and Kotlin will work with you.
Upvotes: 7