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 ...

Get Android Programming with Kotlin for Beginners now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.