Kotlin classes with examples
While retaining the same basic principles of object oriented programming in Java, Kotlin has introduced some smart techniques which are nice enhancements /or extensions to the Java’s object oriented paradigm.
Here is a quick summary of Kotlin’s classes :
- Object instantiation syntax does not contain the new operator. In fact, kotlin has removed the new operator completely.
- No need to add setters and getter methods for the properties of object. Even Lombok is not required, setter and getters are auto generated by Kotlin.
class Computer(var cpuType : String, var ramSize : Int)
var computer = Computer(cpuType = "apple silicon", ramSize = 16)
computer.cpuType = "i9"
computer.ramSize = 64
- The ‘extends’ and ‘implements’ have been replaced by the colon (:) symbol - see how smart it is , compact and effective.
- Multiple classes can exist in a package and there is no need to have the main class name as the file name. No need to have the package hierarchy match directory structure. In fact one of the common practice in Kotlin is to declare all the classes representing value objects or data transfer objects in a single file.
- Data class is a special type of class which is meant as containers for data transport and they are declared with the prefix ‘data’ before the class name. These data classes provide additional methods - toString(),equals(), hashcode(), copy()
data class Computer(var cpuType : String, var ramSize : Int)
- Kotlin classes are by default final, if you have to declare non final classes - you have to declare them as open. Again this has been done intentionally to keep the classes immutable.
Leave a Comment