Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 33
Pass In Values to an Object Using Its Constructor
ОглавлениеAn object in Kotlin can have one or more constructors. A constructor does just what it sounds like: it constructs the object. More specifically, it's a special method that runs when an object is created. It can also take in property values—like that required first and last name.
You put the constructor right after the class definition, like this:
class Person constructor(firstName: String, lastName: String) {
In this case, the constructor takes in two properties: firstName
and lastName
, both String
types. Listing 1.3 shows the entire program in context, along with creating the Person
instance by passing in the values for firstName
and lastName
.
WARNING You'll sometimes hear properties or property values called parameters. That's not wrong; a parameter is usually something passed to something else; in this case, something (a first name and last name) passed to something else (a constructor). But once they're assigned to the object instance, they're no longer parameters. At that point, they are properties (or more accurately, property values) of the object. So it's just easier to call that a property value from the start.
See? The terminology is confusing. Again, though, it will come with time. Just keep going.