Classes in Kotlin: empty classes, constructors and properties

- Andrés Cruz

En español
Classes in Kotlin: empty classes, constructors and properties

The classes in Kotlin, as we will see in the next two posts, are simplified to write the greatest amount of functionality with the least amount of code; the syntax is simple or, in the worst case, similar to that of another language such as Java (remember that it follows the same object-oriented paradigm) with the same concepts of constructors, inheritance, interfaces, and abstract classes as in Java (although with a substantial difference in the management of properties); to define a class in Kotlin we have:

Getting started with classes: empty classes

To define a class in Kotlin in its simplest expression we have to:

class Vacia

As we can see, in Kotlin, to create a public class (by default since no other type of class is defined) it is not necessary to define keys or anything like that, since it does not have properties or another method; We could also define the above class with braces:

class Vacia {}

Although they are optional depending on whether we define properties and methods within the class; but at least we must define a class that we can call as empty, that is to say that it does not have any type of properties or methods in it and the keys.

Instantiate classes:

To instantiate the previous class it would be as follows:

val vacia = Vacia ()

The () are used to indicate the constructor method, which for this example is the default of the Empty class; Also note that we do not use the keyword of other programming languages such as Java new which is used in Java to indicate the creation of a new object.

Although a class with nothing inside or nothing defined doesn't help us much; for that we have the properties that we will see next.

Class properties in Kotlin

The classes serve us to reference objects in the real world, and through the properties we can define the different characteristics that we are interested in manipulating with which that object is recorded; for example, to define a Person class in Kotlin with some properties (yes, properties and not attributes) we can do the following:

class Persona {
var nombre: String = ""
var apellido: String = ""
var edad: Int = 0
}

The properties or properties in substitution of the variables

The properties or properties in Kotlin are something innovative that will make things much easier for us when building our classes; since they replace the getters and setters that we have to use in other languages like Java; With this we achieve a huge simplification in the amount of code that we have to create in our classes that are object-oriented or that define an entity or something like that; for example, a person, we don't have to define the gets and sets for the first name, last name, etc., but simply declare the property as if it were a variable.

Now we are going to create an instance of a class again, in this case the class called Person and we are going to access the properties that we defined previously:

val persona = Persona()
persona.nombre = "Andrés"
persona.apellido = "Cruz"

To access each of them we can just as easily:

println(persona.nombre) println(persona.apellido)

Properties, but not variables in Kotlin classes

A very important point is what we were saying before, there is a change of concept between Kotlin and Java, while in Java the first and last name properties for this example would be fields in Kotlin they are properties, this brings us to the fact that in Java it is considered a bad practice programming that we access the fields directly as we did before, but not in Kotlin, in Kotlin the GET and SET methods are inferred by the compiler, something that does not happen in Java and this is due to this difference in concepts that we pointed out previously; you can get more information in Kotlin Getters and Setters and it is important that you are aware of this paradigm shift and know how to take advantage of it.

Overriding the get and set methods

Of course we can define our own getters and setsters that override the default ones or those inferred by the Kotlin compiler:

class Persona {
var nombre: String = ""
    get() = field
    set(value) {
      field = value
    }
var apellido: String = ""
var edad: Int = 0
}

Class constructors in Kotlin

Main builder

Like all object-oriented programming languages, Kotlin has constructor methods in classes that are used to initialize class values, just like in Java; but unlike the latter, Kotlin incorporates a very interesting way with which we save a few lines of code, changes the methodology and does not define the main constructor as a method within the function but rather embedded within the class:

class Persona(nombre: String, apellido: String, edad: Int) {
var nombre: String = nombre
var apellido: String = apellido
var edad: Int = edad
}

Kotlin defines the main constructor as part of the class in the header of the class, where the parameters are optional.

With this, Koltin automatically makes the equivalence between the parameters in the constructor with the properties defined in the class.

To create an instance initializing from the constructor we have: var person = Persona("Andrés", "Cruz", 27)

To understand this last comment, we could define the constructor method as follows:

class Persona(nombre: String, apellido: String, edad: Int) {
var nombre: String = ""
var apellido: String = ""
var edad: Int = 0

init {
	this.nombre = nombre
	this.apellido = apellido
	this.edad = edad
}

}

This last code would be "the Java way" in that we specify which constructor parameters initialize the properties of the class, internally, this is what Kotlin does with the init{} structure.

Or we could simplify it even more:

    class Persona(nombre: String, apellido: String, edad: Int) {
    var nombre: String = nombre
    var apellido: String = apellido
    var edad: Int = edad

    }

And with this we remove the init structure from our code.

We can also place the word constructor after indicating the name of the class:

class Persona constructor (nombre: String, apellido: String, edad: Int) { var nombre: String = nombre var apellido: String = apellido var edad: Int = edad }

All these examples of main constructors are equivalent, but if we are not going to perform any validation we can leave it using the default constructor:

class Persona(nombre: String, apellido: String, edad: Int) { var nombre: String = "" var apellido: String = "" var edad: Int = 0 }

Instantiating the above class

Regardless of which scheme you prefer, to create an instance of the person class using the constructor, we can do the following:

var persona = Persona("Andrés"," Cruz",27)

Multiple constructors (child constructors)

Taking as main constructor the one that defines (first name: String, last name: String, age: Int) we also define a secondary constructor, which are defined outside the class header but inside the class body as for this constructor example ( firstname: String, lastname: String):

class Persona constructor (nombre: String, apellido: String, edad: Int) {
var nombre: String = ""
var apellido: String = ""
var edad: Int = 0

constructor (nombre: String, apellido: String) : this(nombre, apellido, 0)

}

This way, you can define how many child constructors you want.

Or what is the same:

class Persona (nombre: String, apellido: String, edad: Int) {
var nombre: String = nombre
var apellido: String = apellido
var edad: Int = edad

constructor (nombre: String, apellido: String) : this(nombre, apellido, 0)

}

As we can see, there are multiple combinations according to our preferred scheme; In the next entry we will see the types of classes in Kotlin, inheritance, interfaces and abstract classes in Kotlin.

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.