Classes
Classes are a fundamental building block of OOP. In fact, Kotlin classes are very similar to Java classes. Kotlin, however, allows more functionality together with simpler and much more concise syntax.
Class declaration
Classes in Kotlin are defined using the class
keyword. The following is the simplest class declaration--an empty class named Person
:
class Person
The definition of Person
does not contain any body. Still, it can be instantiated using a default constructor:
val person = Person()
Even such a simple task as class instantiation is simplified in Kotlin. Unlike Java, Kotlin does not require the new
keyword to create a class instance. Due to strong Kotlin interoperability with Java, we can instantiate classes defined in Java and Kotlin exactly the same way (without the new
keyword). The syntax used to instantiate a class depends on the actual language used to create class instance (Kotlin or Java), not the language the class was declared in:
// Instantiate Kotlin...