Название: Programming Kotlin Applications
Автор: Бретт Мак-Лахлин
Издательство: John Wiley & Sons Limited
Жанр: Программы
isbn: 9781119696216
isbn:
WHAT'S IN THIS CHAPTER?
Dive deeper into Kotlin types and variables
More on mutability
Creating custom accessors and mutators
Assignment, during and after variable creation
Type safety and what it means
UPGRADE YOUR KOTLIN CLASS GAME
You've already had a solid introduction to Kotlin, including building your first object. So we're going to get right to work. There's that nagging issue with a person's last name showing incorrectly, but before fixing that, you're ready to up how you build classes from a pre-compile point of view.
So far, you've used a single file to contain both your class ( Person
) and your main
function. That's not scalable, though. Before long, you're going to have lots of classes—and that's classes, not instances of classes.
NOTE As a quick refresher, a class is a definition. You have a Person
class, and you might also have a Car
class or a House
class. An instance of a class is a specific piece of memory that holds a representation of an object. In the last chapter, when you created a brian
or a rose
variable, you assigned those instances of the Person
class.
It's pretty easy to get lots of instances of a class, and then to also have lots of different classes defined as well. In those cases, things get messy if you're just using a single file.
If you throw all your classes into one file, that file is going to be a mess. It's better to separate each of your classes into their own files: one file per class (in general), and then if you have a main
function, give that its own file, too.
Name a File According to Its Class
Go ahead and create a new Kotlin project. You can call it whatever you like; Kotlin_ch02
works if you need a suggestion. Then, in the src/
folder, create a new file called Person
. Your IDE will likely add the .kt
extension for you. Then, just drop in your existing Person
code from Chapter 1. That code is shown again in Listing 2.1 for good measure.
LISTING 2.1: The Person code from Chapter 1
class Person(var firstName: String, var lastName: String) { var fullName: String // Set the full name when creating an instance init { fullName = "$firstName $lastName" } override fun toString(): String { return fullName } }
Now create another file, also in src/
, and call it PersonApp
. You can then drop your existing main
function into that. That bit of code is reprised in Listing 2.2.
LISTING 2.2: Main function for testing the Person class
fun main() { // Create a new person val brian = Person("Brian", "Truesby") println(brian) // Create another person val rose = Person("Rose", "Bushnell") println(rose) // Change Rose's last name rose.lastName = "Bushnell-Truesby" println(rose) }
At this point, you should be able to run PersonApp
just as you did in Chapter 1. Your output should also be the same. You can see in Figure 2.1 the IntelliJ IDE, with the two Kotlin files as tabs, and the output in the bottom pane.
FIGURE 2.1 Your IDE should let you easily get to your source code as well as see output.
WARNING If you get any warnings, the most likely culprit is that you didn't create your Person
and PersonApp
files in the same directory. Make sure both files are in the src/
directory and try again.
At this point, you could go ahead and keep creating more objects in the src/
directory. But there's still a better way!
Organize Your Classes with Packages
While it's great that you've got Person
separate from the test main
function, you've still not really solved the original problem: class organization. If having all your classes in one file is a pain, then by extension, so is having all your classes in a single directory.
What you really want is to organize your classes by functionality. So let's assume that you want your Person
class, but you also think you might later want some specific types of people; maybe a Mother
class or a Child
class. Suppose you're building software to model a genealogy, for example.
In that situation, you really want your classes related to Person
grouped together. But you might also have some classes related to the customer, with their account information: username, password, email. These aren't instances of Person
, they're (perhaps) instances of a User
. You might even have a UserPreferences
class at some point, too, letting you store that user's information. So that might all belong to a group of classes related to User
.
Kotlin—and many other languages—use the concept of packages to provide this organization. A package is just a logical grouping of classes, with a particular namespace: some way to prefix and identify classes as being related. You could have a person
package with Person
, Mother
, Father
, and so forth, and a user
package with User
, UserPreferences
, and the like.
Naming your package is important, though, so a few best practices:
Packages should begin with lowercase letters. Use person instead of Person. (Classes begin with capitals; packages with lowercase.)
Start the package with a dot-separated name that identifies the organization, like org.wiley or com.myCodeShop.
If you might use languages other than Kotlin, you may want to also add kotlin as part of the package name, to distinguish the package from other code (such as Java).
Put all this together and separate the pieces with a dot delimiter (.). For this book, the package will СКАЧАТЬ