Kotlin Class

To declare a class in Kotlin, we use the class statement followed by the name of the class, and inside we introduce the attributes (variables) and methods of the class including the constructor:

class Rectangle {
//define width and height of Rectangle
var l:Double=0.0
var h:Double=0.0
//constructor
class Rectangle(l:Double,h:Double)
}

We can also add the constructor with or without parameters (the constructor is a class method that takes the same name of the class):

//define constructor
class Rectangle(l:Double,h:Double)

Here is the complete classe code :

class Rectangle {
//define width and height of Rectangle
var l:Double=0.0
var h:Double=0.0
//constructor
class Rectangle(l:Double,h:Double)
}

Instanciation 

 The instantiation in Kotlin is easier than Java, it is done via the instruction var followed by the name of the object that you want to create. So in our example above, the instantiation is done as follows:

var R=Rectangle()
// here we create an Rectangle object named R

We can also assign a length and width to rectangle R

//assigning a length and width to the rectangle R
R.l=...
R.h=...

Example

fun main(args: Array< String >) {
var R=Rectangle()
R.l=10.0
R.h=7.0
println("The rectangle's length is : " + R.l)
println("The rectangle's width is : " + R.h)
}

Contracted Form

The Kotlin class can be used in the contracted form :

class Person(var name: String, var age: Int){
}

Thus, the instantiation is done as follows:

fun main(args: Array< String>) {
var P=Person("Davis",37)
println("The Person name is : "+ P.name)
println("The Person's age is : " + P.age)
}
Younes Derfoufi

Leave a Reply