2.1 Objects Everywhere
Objects store data using properties (vals and vars) and perform operations with this data using function.
Some definitions:
•
Class: Defines properties and functions for what is essentially a new data type. Classes are also called user-defined types.
•
Member: Either a property or a function of a class.
•
Member function: A function that works only with a specific class of object.
•
Creating an object: Making a val or var of a class. Also called creating an instance of that class.
Because classes define state and behavior, we can even refer to instances of built-in types like Double or Boolean as objects.
Consider Kotlin's IntRange class:
We create two objects (instances) of the IntRange class. Each object has its own piece of storage in memory. IntRange is a class, but a particular range r1 from 0 to 10 is an object that is distinct from range r2.
Numerous operations are available for an IntRange object. Some are straightforward, like sum(), and others require more understanding before you can use them. If you try calling one that needs arguments, the IDE will ask for those arguments.
To learn about a particular member function, look it up in the Kotlin documentation. Notice the magnifying glass icon in the top right area of the page. Click on that and type IntRange into the search box. Click on kotlin.ranges > IntRange from the resulting search. You'll see the documentation for the IntRange class. You can study all the member functions—the Application Programming Interface (API)—of the class. Although you won't understand most of it at this time, it's helpful to become comfortable looking things up in the Kotlin documentation.
An IntRange is a kind of object, and a defining characteristic of an object is that you perform operations on it. Instead of "performing an operation," we say calling a member function. To call a member function for an object, start with the object identifier, then a dot, then the name of the operation:
Because sum() is a member function defined for IntRange, you call it by saying r.sum(). This adds up all the numbers in that IntRange.
Earlier object-oriented languages used the phrase "sending a message" to describe calling a member function for an object. Sometimes you'll still see that terminology.
Classes can have many operations (member functions). It's easy to explore classes using an IDE (integrated development environment) that includes a feature called code completion. For example, if you type .s after an object identifier within IntelliJ IDEA, it shows all the members of that object that begin with s:
Try using code completion on other objects. For example, you can reverse a String or convert all the characters to lower case:
You can easily convert a String to an integer and back:
Later in the book we discuss strategies to handle situations when the String you want to convert doesn't represent a correct integer value.
You can also convert from one numerical type to another. To avoid confusion, conversions between number types are explicit. For example, you convert an Int i to a Long by calling i.toLong(), or to a Double with i.toDouble():
Well-defined classes are easy for a programmer to understand, and produce code that's easy to read.
2.2 Creating Classes
Not only can you use predefined types like IntRange and String, you can also create your own types of objects.
Indeed, creating new types comprises much of the activity in object-oriented programming. You create new types by defining classes.
An object is a piece of the solution for a problem you're trying to solve. Start by thinking of objects as expressing concepts. As a first approximation, if you discover a "thing" in your problem, represent that thing as an object in your solution.
Suppose you want to create a program to manage animals in a zoo. It makes sense to categorize the different types of animals based on how they behave, their needs, animals they get along with and those they fight with. Everything different about a species of animal is captured in the classification of that animal's object. Kotlin uses the class keyword to create a new type of object:
To define a class, start with the class keyword, followed by an identifier for your new class. The class name must begin with a letter (A-Z, upper or lower case), but can include things like numbers and underscores. Following convention, we capitalize the first letter of a class name, and lowercase the first letter of all vals and vars.
Animals.kt starts by defining three new classes, then creates four objects (also called instances) of those classes.
Giraffe is a class, but a particular five-year-old male giraffe that lives in Botswana is an object. Each object is different from all others, so we give them names like g1 and g2.
Notice the rather cryptic output of the last four lines. The part before the @ is the class name, and the number after the @ is the address where the object is located in your computer's memory. Yes, that's a number even though it includes some letters—it's called "hexadecimal notation". Every object in your program has its own unique address.
The classes defined here (Giraffe, Bear, and Hippo) are as simple as possible: the entire class definition is a single line. More complex classes use curly braces ({ and }) to create a class body containing the characteristics and behaviors for that class.
A function defined within a class belongs to that class. In Kotlin, we call these member functions of the class. Some object-oriented languages like Java choose to call them methods, a term that came from early object-oriented languages like Smalltalk. To emphasize the functional nature of Kotlin, the designers chose to drop the term method, as some beginners found the distinction confusing. Instead, the term function is used throughout the language.
If it is unambiguous, we will just say "function." If we must make the distinction:
•
Member functions belong to a class.
•
Top-level functions exist by themselves and are not part of a class.
Here, bark() belongs to the Dog class:
In main(), we create a Dog object and assign it to val dog. Kotlin emits a warning because we never use dog.
Member functions are called (invoked) with the object name, followed by a . (dot/period), followed by the function name and parameter list. Here we call the meow() function and display the result:
A member function acts on a particular instance of a class. When you call meow(), you must call it with an object. During the call, meow() can access other members of that object.
When calling a member function, Kotlin keeps track of the object of interest by silently passing a reference to that object. That reference is available inside the member function by using the keyword this.
Member functions have special access to other elements within a class, simply by naming those elements. You can also explicitly qualify access to those elements using this. Here, exercise() calls speak() with and without qualification:
In exercise(), we call speak() first with an explicit this and then omit the qualification.
Sometimes you'll see code containing an unnecessary explicit this. That kind of code often comes from programmers who know a different language where this is either required, or part of its style. Using a feature unnecessarily is confusing for the reader, who spends time trying to figure out why you're doing it. We recommend avoiding the unnecessary use of this.
Outside the class, you must say hamster.exercise() and hamster.speak().
2.3 Properties
A property is a var or val that's part of a class.
Defining a property maintains state within a class. Maintaining state is the primary motivating reason for creating a class rather than just writing one or more standalone functions.
A var property can be reassigned, while a val property can't. Each object gets its own storage for properties:
Defining a var or val inside a class looks just like defining it within a function. However, the var or val becomes part of that class, and you must refer to it by specifying its object using dot notation, placing a dot between the object and the name of the property. You can see dot notation used for each reference to percentFull.
The percentFull property represents the state of the corresponding Cup object. c1.percentFull and c2.percentFull contain different values, showing that each object has its own storage.
A member function can refer to a property within its object without using dot notation (that is, without qualifying it):
The add() member function tries to add increase to percentFull but ensures that it doesn't go past 100%.
You must qualify both properties and member functions from outside a class.
You can define top-level properties:
Defining a top-level val is safe because it cannot be modified. However, defining a mutable (var) top-level property is considered an anti-pattern. As your program becomes more complicated, it becomes harder to reason correctly about shared mutable state. If everyone in your code base can access the var counter, you can't guarantee it will change correctly: while inc() increases counter by one, some other part of the program might decrease counter by ten, producing obscure bugs. It's best to guard mutable state within a class. In Constraining Visibility you'll see how to make it truly hidden.
To say that vars can be changed while vals cannot is an oversimplification. As an analogy, consider a house as a val, and a sofa inside the house as a var. You can modify sofa because it's a var. You can't reassign house, though, because it's a val:
Although house is a val, its object can be modified because sofa in class House is a var. Defining house as a val only prevents it from being reassigned to a new object.
If we make a property a val, it cannot be reassigned:
Even though sofa is a var, its object cannot be modified because cover in class Sofa is a val. However, sofa can be reassigned to a new object.
We've talked about identifiers like house and sofa as if they were objects. They are actually references to objects. One way to see this is to observe that two identifiers can refer to the same object:
When kitchen1 modifies table, kitchen2 sees the modification. kitchen1.table and kitchen2.table display the same output.
Remember that var and val control references rather than objects. A var allows you to rebind a reference to a different object, and a valprevents you from doing so.
Mutability means an object can change its state. In the examples above, class House and class Kitchen define mutable objects while class Sofa defines immutable objects.
2.4 Constructors
You initialize a new object by passing information to a constructor.
Each object is an isolated world. A program is a collection of objects, so correct initialization of each individual object solves a large part of the initialization problem. Kotlin includes mechanisms to guarantee proper object initialization.
A constructor is like a special member function that initializes a new object. The simplest form of a constructor is a single-line class definition:
In main(), calling Wombat() creates a Wombat object. If you are coming from another object-oriented language you might expect to see a new keyword used here, but new would be redundant in Kotlin so it was omitted.
You pass information to a constructor using a parameter list, just like a function. Here, the Alien constructor takes a single argument:
Creating an Alien object requires the argument (try it without one). name initializes the greeting property within the constructor, but it is not accessible outside the constructor—try uncommenting line [1].
If you want the constructor parameter to be accessible outside the class body, define it as a var or val in the parameter list:
These class definitions have no explicit class bodies—the bodies are implied.
When name is defined as a var or val, it becomes a property and is thus accessible outside the constructor. val constructor parameters cannot be changed, while var constructor parameters are mutable.
Your class can have numerous constructor parameters:
In Complex Constructors, you'll see that constructors can also contain complex initialization logic.
If an object is used when a String is expected, Kotlin calls the object's toString() member function. If you don't write one, you still get a default toString():
The default toString() isn't very useful—it produces the class name and the physical address of the object (this varies from one program execution to the next). You can define your own toString():
override is a new keyword for us. It is required here because toString() already has a definition, the one producing the primitive result. override tells Kotlin that yes, we do actually want to replace the default toString() with our own definition. The explicitness of overrideclarifies the code and prevents mistakes.
A toString() that displays the contents of an object in a convenient form is useful for finding and fixing programming errors. To simplify the process of debugging, IDEs provide debuggers that allow you to observe each step in the execution of a program and to see inside your objects.
2.5 Constraining Visibility
If you leave a piece of code for a few days or weeks, then come back to it, you might see a much better way to write it.
This is one of the prime motivations for refactoring, which rewrites working code to make it more readable, understandable, and thus maintainable.
There is a tension in this desire to change and improve your code. Consumers (client programmers) require aspects of your code to be stable. You want to change it, and they want it to stay the same.
This is particularly important for libraries. Consumers of a library don't want to rewrite code for a new version of that library. However, the library creator must be free to make modifications and improvements, with the certainty that the client code won't be affected by those changes.
Therefore, a primary consideration in software design is:
Separate things that change from things that stay the same.
To control visibility, Kotlin and some other languages provide access modifiers. Library creators decide what is and is not accessible by the client programmer using the modifiers public, private, protected, and internal. This atom covers public and private, with a brief introduction to internal. We explain protected later in the book.
An access modifier such as private appears before the definition for a class, function, or property. An access modifier only controls access for that particular definition.
A public definition is accessible by client programmers, so changes to that definition impact client code directly. If you don't provide a modifier, your definition is automatically public, so public is technically redundant. You will sometimes still specify public for the sake of clarity.
A private definition is hidden and only accessible from other members of the same class. Changing, or even removing, a private definition doesn't directly impact client programmers.
private classes, top-level functions, and top-level properties are accessible only inside that file:
You can access private top-level properties ([1]), classes([2]), and function([3]) from other functions and classes within RecordAnimals.kt. Kotlin prevents you from accessing a private top-level element from within another file, telling you it's private in the file:
Privacy is most commonly used for members of a class:
•
[1] A private property, not accessible outside the containing class.
•
[2] A private member function.
•
[3] A public member function, accessible to anyone.
•
[4] No access modifier means public.
•
[5] Only members of the same class can access private members.
The private keyword means no one can access that member except other members of that class. Other classes cannot access privatemembers, so it's as if you're also insulating the class against yourself and your collaborators. With private, you can freely change that member without worrying whether it affects another class in the same package. As a library designer you'll typically keep things as private as possible, and expose only functions and classes to client programmers.
Any member function that is a helper function for a class can be made private to ensure you don't accidentally use it elsewhere in the package and thus prohibit yourself from changing or removing that function.
The same is true for a private property inside a class. Unless you must expose the underlying implementation (which is less likely than you might think), make properties private. However, just because a reference to an object is private inside a class doesn't mean some other object can't have a public reference to the same object:
•
[1] c is now defined in the scope surrounding the creation of the CounterHolder object on the following line.
•
[2] Passing c as the argument to the CounterHolder constructor means that the new CounterHolder now refers to the same Counter object that c refers to.
•
[3] The Counter that is supposedly private inside ch can still be manipulated via c.
•
[4] Counter(9) has no other references except within CounterHolder, so it cannot be accessed or modified by anything except ch2.
Maintaining multiple references to a single object is called aliasing and can produce surprising behavior.
Modules
Unlike the small examples in this book, real programs are often large. It can be helpful to divide such programs into one or more modules. A module is a logically independent part of a codebase. The way you divide a project into modules depends on the build system (such as Gradle or Maven) and is beyond the scope of this book.
An internal definition is accessible only inside the module where it is defined. internal lands somewhere between private and public—use it when private is too restrictive but you don't want an element to be a part of the public API. We do not use internal in the book's examples or exercises.
Modules are a higher-level concept. The following atom introduces packages, which enable finer-grained structuring. A library is often a single module consisting of multiple packages, so internal elements are available within the library but are not accessible by consumers of that library.
2.6 Packages
A fundamental principle in programming is the acronym DRY: Don't Repeat Yourself.
Multiple identical pieces of code require maintenance whenever you make fixes or improvements. So duplicating code is not just extra work—every duplication creates opportunities for mistakes.
The import keyword reuses code from other files. One way to use import is to specify a class, function or property name:
A package is an associated collection of code. Each package is usually designed to solve a particular problem, and often contains multiple functions and classes. For example, we can import mathematical constants and functions from the kotlin.math library:
Sometimes you want to use multiple third-party libraries containing classes or functions with the same name. The as keyword allows you to change names while importing:
as is useful if a library name is poorly chosen or excessively long.
You can fully qualify an import in the body of your code. In the following example, the code might be less readable due to the explicit package names, but the origin of each element is absolutely clear:
To import everything from a package, use a star:
The kotlin.math package contains a convenient roundToInt() that rounds the Double value to the nearest integer, unlike toInt()which simply truncates anything after a decimal point.
To reuse your code, create a package using the package keyword. The package statement must be the first non-comment statement in the file. package is followed by the name of your package, which by convention is all lowercase:
You can name the source-code file anything you like, unlike Java which requires the file name to be the same as the class name.
Kotlin allows you to choose any name for your package, but it's considered good style for the package name to be identical to the directory name where the package files are located (this will not always be the case for the examples in this book).
The elements in the pythagorean package are now available using import:
In the remainder of this book we use package statements for any file that defines functions, classes, etc., outside of main(), to prevent name clashes with other files in the book, but we usually won't put a package statement in a file that only contains a main().
2.7 Testing
Constant testing is essential for rapid program development.
If changing one part of your code breaks other code, your tests reveal the problem right away. If you don't find out immediately, changes accumulate and you can no longer tell which change caused the problem. You'll spend a lot longer tracking it down.
Testing is a crucial practice, so we introduce it early and use it throughout the rest of the book. This way, you become accustomed to testing as a standard part of the programming process.
Using println() to verify code correctness is a weak approach—you must scrutinize the output every time and consciously ensure that it's correct.
To simplify your experience while using this book, we created our own tiny testing system. The goal is a minimal approach that:
1.
Shows the expected result of expressions.
2.
Provides output so you know the program is running, even when all tests succeed.
3.
Ingrains the concept of testing early in your practice.
Although useful for this book, ours is not a testing system for the workplace. Others have toiled long and hard to create such test systems. For example:
•
JUnit is one of the most popular Java test frameworks, and is easily used from within Kotlin.
•
Kotest is designed specifically for Kotlin, and takes advantage of Kotlin language features.
•
To use our testing framework, we must first import it. The basic elements of the framework are eq (equals) and neq (not equals):
The code for the atomictest package is in Appendix A: AtomicTest. We don't intend that you understand everything in AtomicTest.kt right now, because it uses some features that won't appear until later in the book.
To produce a clean, comfortable appearance, AtomicTest uses a Kotlin feature you haven't seen yet: the ability to write a function call a.function(b) in the text-like form a function b. This is called infix notation. Only functions defined using the infix keyword can be called this way. AtomicTest.kt defines the infix eq and neq used in TestingExample.kt:
eq and neq are flexible—almost anything works as a test expression. If expected is a String, then expression is converted to a String and the two Strings are compared. Otherwise, expression and expected are compared directly (without converting them first). In either case, the result of expression appears on the console so you see something when the program runs. Even when the tests succeed, you still see the result on the left of eq or neq. If expression and expected are not equivalent, AtomicTest shows an error when the program runs.
The last test in TestingExample.kt intentionally fails so you see an example of failure output. If the two values are not equal, Kotlin displays the corresponding message starting with [Error]. If you uncomment the last line and run the example above, you will see, after all the successful tests:
The actual value stored in v2 is not what it is claimed to be in the "expected" expression. AtomicTest displays the String representations for both expected and actual values.
eq and neq are the basic (infix) functions defined for AtomicTest—it truly is a minimal testing system. When you put eq and neqexpressions in your examples, you'll create both a test and some console output. You verify the correctness of the program by running it.
There's a second tool in AtomicTest. The trace object captures output for later comparison:
Adding results to trace looks like a function call, so you can effectively replace println() with trace().
In previous atoms, we displayed output and relied on human visual inspection to catch any discrepancies. That's unreliable; even in a book where we scrutinize the code over and over, we've learned that visual inspection can't be trusted to find errors. From now on we rarely use commented output blocks because AtomicTest will do everything for us. However, sometimes we still include commented output blocks when that produces a more useful effect.
Seeing the benefits of using testing throughout the rest of the book should help you incorporate testing into your programming process. You'll probably start feeling uncomfortable when you see code that doesn't have tests. You might even decide that code without tests is broken by definition.
Testing as Part of Programming
Testing is most effective when it's built into your software development process. Writing tests ensures you get the results you expect. Many people advocate writing tests before writing the implementation code—you first make the test fail before you write the code to make it pass. This technique, called Test Driven Development (TDD), is a way to ensure that you're really testing what you think you are. You'll find a more complete description of TDD on Wikipedia (search for "Test Driven Development").
There's another benefit to writing testably—it changes the way you craft your code. You could just display the results on the console. But in the test mindset you wonder, "How will I test this?" When you create a function, you decide you should return something from the function, if for no other reason than to test that result. Functions that do nothing but take input and produce output tend to generate better designs, as well.
Here's a simplified example using TDD to implement the BMI calculation from Number Types. First, we write the tests, along with an initial implementation that fails (because we haven't yet implemented the functionality):
Only the first test passes. The other tests fails and are commented. Next, we add code to determine which weights are in which categories. Now all the tests fail:
We're using Ints instead of Doubles, producing a zero result. The tests guide us to the fix:
You may choose to add additional tests for the boundary conditions.
In the exercises for this book, we include tests that your code must pass.
2.8 Exceptions
The word "exception" is used in the same sense as the phrase "I take exception to that."
An exceptional condition prevents the continuation of the current function or scope. At the point the problem occurs, you might not know what to do with it, but you cannot continue within the current context. You don't have enough information to fix the problem. So you must stop and hand the problem to another context that's able to take appropriate action.
This atom covers the basics of exceptions as an error-reporting mechanism. In Section VI: Preventing Failure, we look at other ways to deal with problems.
It's important to distinguish an exceptional condition from a normal problem. A normal problem has enough information in the current context to cope with the issue. With an exceptional condition, you cannot continue processing. All you can do is leave, relegating the problem to an external context. This is what happens when you throw an exception. The exception is the object that is "thrown" from the site of the error.
Consider toInt(), which converts a String to an Int. What happens if you call this function for a String that doesn't contain an integer value?
Uncommenting line [1] produces an exception. Here, the failing line is commented so we don't stop the book's build, which checks whether each example compiles and runs as expected.
When an exception is thrown, the path of execution—the one that can't be continued—stops, and the exception object ejects from the current context. Here, it exits the context of erroneousCode() and goes out to the context of main(). In this case, Kotlin only reports the error; the programmer has presumably made a mistake and must fix the code.
When an exception isn't caught, the program aborts and displays a stack trace containing detailed information. Uncommenting line [1] in ToIntException.kt, produces the following output:
The stack trace gives details such as the file and line where the exception occurred, so you can quickly discover the issue. The last two lines show the problem: in line 10 of main() we call erroneousCode(). Then, more precisely, in line 6 of erroneousCode() we call toInt().
To avoid commenting and uncommenting code to display exceptions, we use the capture() function from the AtomicTest package:
Using capture(), we compare the generated exception to the expected error message. capture() isn't very helpful for normal programming—it's designed specifically for this book, so you can see the exception and know that the output has been checked by the book's build system.
Another strategy when you can't successfully produce the expected result is to return null, which is a special constant denoting "no value." You can return null instead of a value of any type. Later in Nullable Types we discuss the way null affects the type of the resulting expression.
The Kotlin standard library contains String.toIntOrNull() which performs the conversion if the String contains an integer number, or produces null if the conversion is impossible—null is a simple way to indicate failure:
Suppose we calculate average income over a period of months:
If months is zero, the division in averageIncome() throws an ArithmeticException. Unfortunately, this doesn't tell us anything about why the error occurred, what the denominator means and whether it can legally be zero in the first place. This is clearly a bug in the code—averageIncome() should cope with a months of 0 in a way that prevents a divide-by-zero error.
Let's modify averageIncome() to produce more information about the source of the problem. If months is zero, we can't return a regular integer value as a result. One strategy is to return null:
If a function can return null, Kotlin requires that you check the result before using it (this is covered in Nullable Types). Even if you only want to display output to the user, it's better to say "No full month periods have passed," rather than "Your average income for the period is: null."
Instead of executing averageIncome() with the wrong arguments, you can throw an exception—escape and force some other part of the program to manage the issue. You could just allow the default ArithmeticException, but it's often more useful to throw a specific exception with a detailed error message. When, after a couple of years in production, your application suddenly throws an exception because a new feature calls averageIncome() without properly checking the arguments, you'll be grateful for that message:
•
[1] When throwing an exception, the throw keyword is followed by the exception to be thrown, along with any arguments it might need. Here we use the standard exception class IllegalArgumentException.
Your goal is to generate the most useful messages possible to simplify the support of your application in the future. Later you'll learn to define your own exception types and make them specific to your circumstances.
2.9 Lists
A List is a container, which is an object that holds other objects.
Containers are also called collections. When we need a basic container for the examples in this book, we normally use a List.
Lists are part of the standard Kotlin package so they don't require an import.
The following example creates a List populated with Ints by calling the standard library function listOf() with initialization values:
•
[1] A List uses square brackets when displaying itself.
•
[2] for loops work well with Lists: for(i in ints) means i receives each value in ints. You don't declare val i or give its type; Kotlin knows from the context that i is a for loop identifier.
•
[3] Square brackets index into a List. A List keeps its elements in initialization order, and you select them individually by number. Like most programming languages, Kotlin starts indexing at element zero, which in this case produces the value 99. Thus an index of 4produces the value 11.
Forgetting that indexing starts at zero produces the so-called off-by-one error. In a language like Kotlin we often don't select elements one at a time, but instead iterate through an entire container using in. This eliminates off-by-one errors.
If you use an index beyond the last element in a List, Kotlin throws an ArrayIndexOutOfBoundsException:
A List can hold all different types. Here's a List of Doubles and a List of Strings:
This shows some of List's operations. Note the name "sorted" instead of "sort." When you call sorted() it produces a new List containing the same elements as the old, in sorted order-but it leaves the original List alone. Calling it "sort" implies that the original List is changed directly (a.k.a. sorted in place). Throughout Kotlin, you see this tendency of "leaving the original object alone and producing a new object." reversed() also produces a new List.
Parameterized Types
We consider it good practice to use type inference—it tends to make the cleaner and easier to read. Sometimes, however, Kotlin complains that it can't figure out what type to use, and in other cases explicitness makes the code more understandable. Here's how we tell Kotlin the type contained by a List:
Kotlin uses the initialization values to infer that numbers contains a List of Ints, while strings contains a List of Strings.
numbers2 and strings2 are explicitly-typed versions of numbers and strings, created by adding the type declarations List<Int> and List<String>. You haven't seen angle brackets before—they denote a type parameter, allowing you to say, "this container holds 'parameter' objects." We pronounce List<Int> as "List of Int."
Type parameters are useful for components other than containers, but you often see them with container-like objects.
Return values can also have type parameters:
Kotlin infers the return type for inferred(), while explicit() specifies the function return type. You can't just say it returns a List; Kotlin will complain, so you must give the type parameter as well. When you specify the return type of a function, Kotlin enforces your intention.
Read-Only and Mutable Lists
If you don't explicitly say you want a mutable List, you won't get one. listOf() produces a read-only List that has no mutating functions.
If you're creating a List gradually (that is, you don't have all the elements at creation time), use mutableListOf(). This produces a MutableList that can be modified:
You can add elements to a MutableList using add() and addAll(), or the shortcut += which adds a single element or another collection. Because list has no initial elements, we must tell Kotlin what type it is by providing the <Int> specification in the call to mutableListOf().
A MutableList can be treated as a List, in which case it cannot be changed. You can't, however, treat a read-only List as a MutableList:
Note that list lacks mutation functions despite being originally created using mutableListOf() inside getList(). During the return, the result type becomes a List<Int>. The original object is still a MutableList, but it is viewed through the lens of a List.
A List is read-only—you can read its contents but not write to it. If the underlying implementation is a MutableList and you retain a mutable reference to that implementation, you can still modify it via that mutable reference, and any read-only references will see those changes. This is another example of aliasing, introduced in Constraining Visibility:
first is an immutable reference (val) to the mutable object produced by mutableListOf(1). Then second is aliased to first, so it is a view of that same object. second is read-only because List<Int> does not include modification functions. Note that, without the explicit List<Int> type declaration, Kotlin would infer that second was also a reference to a mutable object.
We're able to add an element (2) to the object because first is a reference to a mutable List. Note that second observes these changes—it cannot change the List although the List changes via first.
Difference of "+=" Between Mutable and Immutable
이 부분은 책에 있는 내용이 아니라 내가 추가적으로 정리하고 싶은 부분임
•
리스트(List)에 대해 += 연산을 하는 경우, 리스트가 Mutable이냐 Immutable이냐에 따라 동작 방식이 다름
•
Mutable: 기존 리스트에 요소(element)를 추가함
•
Immutable: 기존 리스트에 요소가 추가된 새로운 리스트를 생성하여 반환
2.10 Variable Argument Lists
The varargs keyword produces a flexibly-sized argument list.
In Lists we introduced listOf(), which takes any number of parameters and produces a List:
Using the varargs keyword, you can define a function that takes any number of arguments, just like listOf() does. varargs is short for variable argument list:
A function definition may specify only one parameter as vararg. Although it's possible to specify any item in the parameter list as vararg, it's usually simplest to do it for the last one.
vararg allows you to pass any number (including zero) of arguments. All arguments must be of the specified type. vararg arguments are accessed using the parameter name, which becomes an Array:
Although Arrays and Lists look similar, they are implemented differently—List is a regular library class while Array has special low-level support. Array comes from Kotlin's requirement for compatibility with other languages, especially Java.
In day-to-day programming, use a List when you need a simple sequence. Use Arrays only when a third-party API requires an Array, or when you're dealing with varargs.
In most cases you can just ignore the fact that vararg produces an Array and treat it as if it were a List:
You can pass an Array of elements wherever a varargs is accepted. To create an Array, use arrayOf() in the same way you use listOf(). Note that an Array is always mutable. To convert an Array into a sequence of arguments (not just a single element of type Array), use the spread operator, *:
If you pass an Array of primitive types (like Int, Double or Boolean) as in the example above, the Array creation function must be specifically typed. If you use arrayOf(4, 5) instead of intArrayOf(4, 5), line [1] will produce an error complaining that inferred type is Array but IntArray was expected.
The spread operator only works with arrays. If you have a List that you want to pass as a sequence of arguments, first convert it to an Arrayand then apply the spread operator, as in [2]. Because the result is an Array of a primitive type, we must again use the specific conversion function toIntArray().
The spread operator is especially helpful when you must pass vararg arguments to another function that also expects varargs:
Command-Line Arguments
When invoking a program on the command line, you can pass it a variable number of arguments. To capture command-line arguments, you must provide a particular parameter to main():
The parameter is traditionally called args (although you can call it anything), and the type for args can only be Array<String> (Array of String).
If you are using IntelliJ IDEA, you can pass program arguments by editing the corresponding "Run configuration," as shown in the last exercise for this atom.
You can also use the kotlinc compiler to produce a command-line program. If kotlinc isn't on your computer, follow the instructions on the Kotlin main site. Once you've entered and saved the code for MainArgs.kt, type the following at a command prompt:
You provide the command-line arguments following the program invocation, like this:
You'll see this output:
If you want to turn a String parameter into a specific type, Kotlin provides conversion functions, such as a toInt() for converting to an Int, and toFloat() for converting to a Float. Using these assumes that the command-line arguments appear in a particular order. Here, the grogram expects a String, followed by something convertible to an Int, followed by something convertible to a Float:
The first line in main() quits the program if there aren't enough arguments. If you don't provide something convertible to an Int and a Float as the second and third command-line arguments, you will see runtime errors (try it to see the errors).
Compile and run MainArgConversion.kt with the same command-line arguments we used before, and you'll see:
hamster 42 3.14159
2.11 Sets
A Set is a collection that allows only one element of each value.
The most common Set activity is to test for membership using in or cotains():
This example shows:
1.
Placing duplicate items into a Set automatically removes those duplicates.
2.
Element order is not important for sets. Two sets are equal if they contain the same elements.
3.
Both in and contains() test for membership.
4.
You can perform the usual Venn-diagram operations like checking for subset, union, intersection and difference, using either dot notation (set.union(other)) or infix notation (set intersect other). The functions union, intersect and subtract can be used with infix notation.
5.
Set difference can be expressed with either subtract() or the minus operator.
To remove duplicates from a List, convert it to a Set:
You can also use distinct(), which returns a List. You may call toSet() on a String to convert it into a set of unique characters.
As with List, Kotlin provides two creation functions for Set. The result of setOf() is read-only. To create a mutable Set, use mutableSetOf():
The oeprators += and -= add and remove elements to Sets, just as with Lists.
2.12 Maps
A Map connects keys to values and looks up a value when given a key.
You create a Map by providing key-value pairs to mapOf(). Using to, we separate each key from its associated value:
•
[1] The [] operator looks up a value using a key. You can produce all the keys using keys and all the values using values. Calling keys produces a Set because all keys in a Map must be unique, otherwise you'd have ambiguity during a lookup.
•
[2] Iterating through a Map produces key-value pairs as map entries.
•
[3] You can unpack keys and values as you iterate.
A plain Map is read-only. Here's a MutableMap:
map[key] = value adds or changes the value associated with key. You can also explicitly add a pair by saying map += key to value.
mapOf() and mutableMapOf() preserve the order in which the elements are put into the Map. This is not guaranteed for other types of Map.
A read-only Map doesn't allow mutations:
The definition of m creates a Map associating Ints with Strings. If we try to replace a String, Kotlin emits an error.
An expression with + creates a new Map that includes both the old elements and the new one, but doesn't affect the original Map. The only way to "add" an element to a read-only Map is by creating a new Map.
A Map returns null if it doesn't contain an entry for a given key. If you need a result that can't be null, use getValue() and catch NoSuchElementException if the key is missing:
getOrDefault() is usually a nicer alternative to null or an exception.
You can store class instances as values in a Map. Here's a map that retrieves a Contact using a number String:
It's possible to use class instances as keys in a Map, but that's trickier so we discuss it later in the book.
Maps look like simple little databases. They are sometimes called associative arrays, because they associate keys with values. Although they are quite limited compared to a full-featured database, they are nonetheless remarkably useful (and far more efficient than a database).
2.13 Property Accessors
To read a property, use tis name. To assign a value to a mutable property, use the assignment operator =.
This reads and writes the property i:
This appears to be straightforward access to the piece of storage named i. However, Kotlin calls functions to perform the read and write operations. As you expect, the default behavior of those functions reads and writes the data stored in i. In this atom you'll learn to write your own property accessors to customize the reading and writing actions.
The accessor used to get the value of a property is called a getter. You create a getter by defining get() immediately after the property definition. The accessor used to modify a mutable property is called a setter. You create a setter by defining set() immediately after the property definition.
The property accessors defined in the following example imitate the default implementations generated by Kotlin. We display additional information so you can see that the property accessors are indeed called during reads and writes. We indent get() and set() to visually associate them with the property, but the actual association happens because get() and set() are defined immediately after that property (Kotlin doesn't care about the indentation):
The definition order for get() and set() is unimportant. You can define get() without defining set(), and vice-versa.
The default behavior for a property returns its stored value from a getter and modifies it with a setter—the actions of [1] and [2]. Inside the getter and setter, the stored value is manipulated indirectly using the field keyword, which is only accessible within these two functions.
This next example uses the default implementation of the getter and adds a setter to trace changes to the property n:
If you define a property as private, both accessors become private. you can also make the setter private and the getter public. Then you can read the property outside the class, but only change its value inside the class:
Using private set, we control the value property so it can only be incremented by one.
Normal properties store their data in a field. You can also create a property that doesn't have a field:
The properties capacity and full contain no underlying state-they are computed at the time of each access. Both capacity and full are similar to function, and you can define them as such:
In this case, using properties improves readability because capacity and fullness are properties of the case. However, don't just convert all your function to properties—first see how they read.
The Kotlin style guide prefers properties over functions when the value is cheap to calculate and the property returns the same result for each invocation as long as the object state hasn't changed.
Property accessors provide a kind of protection for properties. Many object-oriented languages rely on making a physical field private to control access to that property. With property accessors you can add code to control or modify that access, while allowing anyone to use a property.