Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 41

LISTING 1.5: Converting data to actual properties

Оглавление

class Person(val firstName: String, val lastName: String) { override fun toString(): String { return "$firstName $lastName" } } fun main() { val brian = Person("Brian", "Truesby") println(brian) }

You should get a single line of output:

Brian Truesby

Obviously, the name will be different if you passed in different values for first and last name, but the result is the same, and it's a big deal. You've now:

 Created a new object

 Defined a constructor for the object

 Accepted two pieces of data in that constructor and stored them as properties associated with the object instance

 Overridden a method and made it useful

 Written a main function

 Instantiated your custom object and passed in values

 Used the object to print itself out, using your overridden method

Not too bad for getting started! There's just one more detail to work through before closing shop on your first foray into Kotlin.

Programming Kotlin Applications

Подняться наверх