-
Book Overview & Buying
-
Table Of Contents
Android Programming for Beginners - Fourth Edition
By :
We learned about and used some basic constructors in the previous chapter. We saw that you can declare properties, val or var, with or without default values in the parentheses of the class declaration, just like parameters in a function. However, there is more to constructors, and this section will take our understanding further.
Throughout this chapter and the last, we have been instantiating objects of our classes and have gone into some depth on the various syntax. There is one small part of the code we have been ignoring until now. The following code we have seen several times before; I have highlighted a small part so we can discuss it further.
val soldier = Soldier()
The brackets at the end of the code that initialize the object look just like the ones we used when calling a function (without any parameters). That is, in fact, precisely what is happening. When we declare a class, Kotlin provides (behind the scenes) a special function called a constructor that prepares...