ТОП просматриваемых книг сайта:
Programming Kotlin Applications. Бретт Мак-Лахлин
Читать онлайн.Название Programming Kotlin Applications
Год выпуска 0
isbn 9781119696216
Автор произведения Бретт Мак-Лахлин
Жанр Программы
Издательство John Wiley & Sons Limited
Command-Line Kotlin on UNIX-Based Systems
If you're not on Mac OS X but still have a Unix flavor of operating system, you can use SDKMAN! (sdkman.io
) for installing Kotlin.
NOTE To be accurate, Mac OS X is a Unix-based operating system, so you can use the SDKMAN! instructions for Macs instead of Homebrew or MacPorts.
First, get SDKMAN!:
brett $ curl -s https://get.sdkman.io | bash
When you're finished, you'll need to open a new terminal or shell window or source the modified file as indicated at the end of the installation process.
Now, install Kotlin:
brett $ sdk install kotlin
Verify Your Command-Line Installation
However you've chosen to install Kotlin, when you're finished, you should be able to validate your installation with this command:
brett $ kotlinc
WARNING At this point, you may get prompted to install a Java runtime. This should fire up your system to handle this, and you can accept the prompts without a lot of worry. Find the JDK or JRE for your system, download it, and run it. Then come back and try out kotlinc
again.
If you have your system appropriately configured with Java, you should get back something like this:
brett $ kotlinc Java HotSpot(TM) 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release. Welcome to Kotlin version 1.3.61 (JRE 13.0.2+8) Type :help for help, :quit for quit >>>
This is the Kotlin REPL (Read-Eval-Print Loop), a tool for quickly evaluating Kotlin statements. We'll look at this in more detail later, but for now, exit the REPL by typing :quit .
You can also verify your version of Kotlin with the following command:
brett $ kotlin -version Kotlin version 1.3.61-release-180 (JRE 13.0.2+8)
At this point, you're ready to roll!
CREATING USEFUL OBJECTS
With a working Kotlin environment, it's time to go make that Person
class from Listing 1.2 something less vacuous. As mentioned earlier, objects should model real-world objects. Specifically, if an object represents a “thing” in the world (or in formal circles you'll sometimes hear that objects are “nouns”), then it should have the properties or attributes of that thing, too.
A person's most fundamental property is their name, specifically a first name and last name (or surname, if you like). These can be represented as properties of the object. Additionally, these are required properties; you really don't want to create a person without a first and last name.
For required properties, it's best to require those properties when creating a new instance of an object. An instance is just a specific version of the object; so you might have multiple instances of the Person
class, each one representing a different actual person.
WARNING As you may already be figuring out, there's a lot of technical vocabulary associated with classes. Unfortunately, it will get worse before it gets better: instances and instantiation and constructors and more. Don't get too worried about catching everything right away; just keep going, and you'll find that the vocabulary becomes second nature faster than you think. In Chapter 3, you'll dive in deeper, and in fact, you'll keep revisiting and growing your class knowledge throughout the entire book.
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.
LISTING 1.3: A less useless object in Kotlin and its constructor
class Person constructor(firstName: String, lastName: String) { /* This class still doesn't do much! */ } fun main() { val brian = Person("Brian", "Truesby") }
Now the class takes in a few useful properties. But, as most developers know, there's a tendency to condense things in code. There's a general favoring of typing less, rather than typing more. (Note that this rarely applies to book authors!) So Listing 1.3 can be condensed; you can just drop the word constructor
and things work the same way. Listing 1.4 shows this minor condensation (and arguable improvement).
LISTING 1.4: Cutting out the constructor keyword
class Person(firstName: String, lastName: String) { /* This class still doesn't do much! */ } fun main() { val brian = Person("Brian", "Truesby") }
Print an Object with toString()
This is definitely getting a little better. But the output is still empty, and the class is still basically useless. However, Kotlin gives you some things for free: most notably for now, every class automatically gets a toString()
method. You can run this method by creating an instance of the class (which you've already done) and then calling that method, like this:
val brian = Person("Brian", "Truesby") println(brian.toString())
Make this change to your main
function. Create a new Person
(give it any name you want), and then print the object instance using println
and passing into println
the result of toString()
.
NOTE You may be wondering where in the world that toString()
method came from. (If not, that's OK, too.) It does seem to sort of magically appear. But it's not magical it all. It's actually inherited. Inheritance is closely related to objects, and something we'll talk about in a lot more detail in both Chapter 3 and Chapter 5.