Kotlin is an object-oriented language that allows you to define classes with member variables (member variables are called properties in Kotlin) and methods.
Since almost all classes have constructors, Kotlin offers a condensed syntax that allows you to define the constructor more efficiently when you declare a class.
Here is a simple example:
class Rectangle(var width : Double,var height : Double)
This declaration introduces a class Rectangle with two member variables, width and height. The declaration simultaneously defines the constructor for the class, which takes two parameters.
Creating instances of classes is similar to the syntax in Java, except Kotlin does not use the new keyword:
val r = Rectangle(25.0,15.0)
Methods are simply functions defined in the context of a class:
class Rectangle(var width : Double,var height : Double) {
fun area() : Double = width*height
}
val r = Rectangle(25.0,15.0)
println("The area of r is $(r.area()).")
An alternative approach is to use a computed property, which is a property that has a getter without a setter:
class Rectangle(var width : Double,var height : Double) {
val area() : Double
get() = this.width * this.height
}
val r = Rectangle(25.0,15.0)
println("The area of r is $(r.area).")