Constructors
Throughout this chapter we have been instantiating objects (instances of classes) and we have gone into some depth about the various syntax. There is one small part of the code we have been ignoring until now. This next code we have seen several times before, but I have highlighted a small part of it so we can discuss it further:
val soldier = Soldier()
The brackets on the end of the code that initialize the object looks just like code from the previous chapter when we called a function (without any parameters). That is, in fact, exactly what is happening. When we declare a class, Kotlin provides (behind the scenes) a special function called a constructor that prepares the instance.
So far in this chapter, we have declared and initialized all our instances in a single line each. Often, we will need to use some more logic in initialization, and often we will need to allow the code that initializes an instance of a class to pass in some values (just like a function). This is the...