Skip to content

Commit 246290b

Browse files
Merge pull request Kotlin#46 from p7nov/special-classes-revised
docs: revised Special classes
2 parents f612624 + aa98e52 commit 246290b

File tree

5 files changed

+107
-100
lines changed

5 files changed

+107
-100
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
# Special classes
1+
# Special Classes
Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,27 @@
1-
# Data classes
1+
# Data Classes
22

3-
_Data classes_ make it easy to declare classes that are used to store some values.
4-
Everything that's needed to use them in collections, have a useful string
5-
representation, and create copies is auto-generated.
3+
[Data classes](https://kotlinlang.org/docs/reference/data-classes.html) make it easy to create classes that are used to store values. Such classes are automatically provided with methods for copying, getting a string representation, and using instances in collections.
64

75
<div class="language-kotlin" theme="idea" data-min-compiler-version="1.3">
86

97
```kotlin
10-
data class User(val name: String, val id: Int)
8+
data class User(val name: String, val id: Int) // 1
119

1210
fun main() {
1311
val user = User("Alex", 1)
14-
println(user) // 1
12+
println(user) // 2
1513

1614
val secondUser = User("Alex", 1)
1715
val thirdUser = User("Max", 2)
1816

19-
println("user == secondUser: ${user == secondUser}") // 2
17+
println("user == secondUser: ${user == secondUser}") // 3
2018
println("user == thirdUser: ${user == thirdUser}")
2119

22-
println(user.hashCode()) // 3
20+
println(user.hashCode()) // 4
2321
println(thirdUser.hashCode())
2422

2523
// copy() function
26-
println(user.copy()) // 4
27-
println(user.copy("Max", 2)) // 5
24+
println(user.copy()) // 5
2825
println(user.copy("Max")) // 6
2926
println(user.copy(id = 2)) // 7
3027

@@ -35,11 +32,11 @@ fun main() {
3532

3633
</div>
3734

38-
1. Method `toString` is auto-generated, which makes `println` output look nice.
39-
2. Auto-generated `equals` makes data classes with equal information equals as well.
40-
3. Equal data classes have equal `hashCode()`.
41-
4. Predefined `copy` function makes it easy to obtain a new instance.
42-
5. Property values can be changed on copy. The order corresponds to constructor argument order.
43-
6. It is possible to change only some values.
44-
7. Use named arguments to change the second value without altering the first one.
45-
8. Additionally special `componentN` functions are generated.
35+
1. Defines a data class with the `data` modifier.
36+
2. Method `toString` is auto-generated, which makes `println` output look nice.
37+
3. Auto-generated `equals` considers two instances equal if all their properties are equal.
38+
4. Equal data class instances have equal `hashCode()`.
39+
5. Auto-generated `copy` function makes it easy to create a new instance.
40+
6. When copying, you can change values of certain properties. `copy` accepts areguments in the same order as the class constructor.
41+
7. Use `copy` with named arguments to change the value despite of the properties order.
42+
8. Auto-generated `componentN` functions let you get the values of properties in the order of declaration.
Lines changed: 38 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
# Enum Classes
22

3-
Enum classes are used to model types that represent a finite set of distinct values, such as directions, states, modes and so forth.
4-
5-
They may contain properties and methods like other classes, separated from the enum instances by a semicolon.
3+
[Enum classes](https://kotlinlang.org/docs/reference/enum-classes.html) are used to model types that represent a finite set of distinct values, such as directions, states, modes, and so forth.
64

75
<div class="language-kotlin" theme="idea" data-min-compiler-version="1.3">
86

@@ -11,38 +9,53 @@ enum class State {
119
IDLE, RUNNING, FINISHED // 1
1210
}
1311

14-
enum class Color(val rgb: Int) { // 2
15-
RED(0xFF0000), // 3
12+
fun main() {
13+
val state = State.RUNNING // 2
14+
val message = when (state) { // 3
15+
State.IDLE -> "It's idle"
16+
State.RUNNING -> "It's running"
17+
State.FINISHED -> "It's finished"
18+
}
19+
println(message)
20+
}
21+
22+
```
23+
24+
</div>
25+
26+
1. Defines a simple enum class with three enum instances. The number of instances is always finite and they are all distinct.
27+
2. Accesses an enum instance via the class name.
28+
3. With enums, the compiler can infer if a `when`-expression is exhaustive so that you don't need the `else`-case.
29+
30+
Enums may contain properties and methods like other classes, separated from the list of instances by a semicolon.
31+
32+
<div class="language-kotlin" theme="idea" data-min-compiler-version="1.3">
33+
34+
```kotlin
35+
36+
enum class Color(val rgb: Int) { // 1
37+
RED(0xFF0000), // 2
1638
GREEN(0x00FF00),
1739
BLUE(0x0000FF),
1840
YELLOW(0xFFFF00);
1941

20-
fun containsRed() = (this.rgb and 0xFF0000 != 0) // 4
42+
fun containsRed() = (this.rgb and 0xFF0000 != 0) // 3
2143
}
2244

2345
fun main() {
24-
val red = Color.RED // 5
25-
println(red) // 6
26-
println(red.containsRed())
27-
println(Color.BLUE.containsRed())
28-
29-
val state = State.RUNNING
30-
val message = when (state) { // 7
31-
State.IDLE -> "It's idle"
32-
State.RUNNING -> "It's running"
33-
State.FINISHED -> "It's finished"
34-
}
35-
println(message)
46+
val red = Color.RED
47+
println(red) // 4
48+
println(red.containsRed()) // 5
49+
println(Color.BLUE.containsRed()) // 6
3650
}
3751

3852
```
3953

4054
</div>
4155

42-
1. A simple enum class with three enum instances (note that instances are finite and distinct).
43-
2. An enum class with a property and a method.
44-
3. Each instance must pass an argument for the constructor parameter.
45-
4. Members are separated from the instance definitions with a semicolon.
46-
5. Enum instances are accessed directly via the class name.
47-
6. The default `toString` returns the name of the instance, here `"RED"`.
48-
7. With enums, the compiler can infer if a `when`-expression is exhaustive so that you don't need an `else`-case.
56+
1. Defines an enum class with a property and a method.
57+
2. Each instance must pass an argument for the constructor parameter.
58+
3. Enum class members are separated from the instance definitions by a semicolon.
59+
4. The default `toString` returns the name of the instance, here `"RED"`.
60+
5. Calls a method on a enum instance.
61+
6. Calls a method via enum class name.
Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
# Sealed Classes
22

3+
[Sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) let you restrict the use of inheritance. Once you declare a class sealed, nobody else can create its subclasses.
4+
35
<div class="language-kotlin" theme="idea" data-min-compiler-version="1.3">
46

57
```kotlin
68
sealed class Mammal(val name: String) // 1
79

8-
class Cat(val catName: String) : Mammal(catName)
10+
class Cat(val catName: String) : Mammal(catName) // 2
911
class Human(val humanName: String, val job: String) : Mammal(humanName)
1012

1113
fun greetMammal(mammal: Mammal): String {
12-
when (mammal) { // 2
13-
is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}" // 3
14-
is Cat -> return "Hello ${mammal.name}" // 4
15-
// 5
16-
}
14+
when (mammal) { // 3
15+
is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}" // 4
16+
is Cat -> return "Hello ${mammal.name}" // 5
17+
} // 6
1718
}
1819

1920
fun main() {
@@ -24,11 +25,11 @@ fun main() {
2425
</div>
2526

2627

27-
1. A sealed class is defined with two subclasses which must be in the same file
28-
2. The sealed class is used as an argument for a *when* expression
29-
3. A smartcast is performed, casting Mammal to Human
30-
4. A smartcast is performed, casting Mammal to Cat
31-
5. The *else* clause is not necessary because all subclasses of the sealed class are covered.
32-
This is contrary to ordinary super classes, where an *else* would always be needed.
28+
1. Defines a sealed class.
29+
2. Defines subclasses. Note that all subclasses must be in the same file.
30+
3. Uses an instance of the sealed class as an argument in a `when` expression.
31+
4. A smartcast is performed, casting `Mammal` to `Human`.
32+
5. A smartcast is performed, casting `Mammal` to `Cat`.
33+
6. The `else`-case is not necessary here since all possible subclasses of the sealed class are covered. With a non-sealed superclass `else` would be required.
3334

3435

Lines changed: 40 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
1-
# Object keyword
1+
# Object Keyword
22

3-
First of all, let's start with some basic OOP concepts: a *class* is a blueprint, and an *object* is an instance of a class.
4-
You define a class, then create multiple instances of that class:
3+
Classes and objects in Kotlin work the same way as in most object-oriented languages: a *class* is a blueprint, and an *object* is an instance of a class. Usually, you define a class and then create multiple instances of that class:
54

65
<div class="language-kotlin" theme="idea" data-min-compiler-version="1.3">
76

87
```kotlin
98
import java.util.Random
109

11-
class LuckDispatcher{ //1
10+
class LuckDispatcher { //1
1211
fun getNumber() { //2
1312
var objRandom = Random()
1413
println(objRandom.nextInt(90))
1514
}
1615
}
1716

18-
fun main(){
17+
fun main() {
1918
val d1 = LuckDispatcher() //3
2019
val d2 = LuckDispatcher()
2120

@@ -26,24 +25,24 @@ fun main(){
2625

2726
</div>
2827

29-
1. blueprint definition
30-
2. method definition
31-
3. instance creation
32-
4. method calls
28+
1. Defines a blueprint.
29+
2. Defines a method.
30+
3. Creates instances.
31+
4. Calls the method on instances.
3332

34-
Easy: we create two objects, both *instances* of LuckDispatcher class.
33+
In Kotlin you also have the [**object** keyword](https://kotlinlang.org/docs/reference/object-declarations.html). It is used to obtain a *data type with a single implementation*.
3534

36-
In Kotlin you have also an **object** keyword. What is? is a *data type with a single implementation*.
35+
If you are a Java user and want to understand what "*single*" means, you can think of the **Singleton** pattern:
36+
it ensures you that only one instance of that class is created even if 2 threads try to create it.
3737

38-
If you are a Java user and want to understand what "*single*" means, you can think to Singleton pattern:
39-
it allows you to check that one (and only one) instance of that class will be created, even if 2 threads access it.
38+
To achieve this in Kotlin, you only need to declare an `object`: no class, no constructor, only a lazy instance.
39+
Why lazy? Because it will be created once when the object is accessed. Otherwise, it won't even be created.
4040

41-
To achieve that in Kotlin, you only need to declare an **object**: no class, no constructor, only a lazy instance.
42-
Why lazy? because it will be created one time, if object is used, otherwise, no.
41+
### `object` Expression
4342

44-
In this example, you see a typical basic usage of an **object expression**: a simple object/properties structure.
45-
No need of class declaration: create a single object, declare members and access it.
46-
Object like that, is often used like anonymous class in Java.
43+
Here is a basic typical usage of an `object` **expression**: a simple object/properties structure.
44+
There is no need to do so in class declaration: you create a single object, declare its members and access it within one function.
45+
Objects like this are often created in Java as anonymous class instances.
4746

4847
<div class="language-kotlin" theme="idea" data-min-compiler-version="1.3">
4948

@@ -62,22 +61,22 @@ fun rentPrice(standardDays: Int, festivityDays: Int, specialDays: Int): Unit {
6261

6362
}
6463

65-
66-
fun main(){
64+
fun main() {
6765
rentPrice(10, 2, 1) //5
6866
}
6967
```
7068

7169
</div>
7270

73-
1. Create a rentPrice function, w/ parameters (regular days, festivity days, special days)
74-
2. Create rates object, where you set vars values
75-
3. Access object's vars
76-
4. Print total
77-
5. Access the instance (initialization), calling fun
71+
1. Creates a function with parameters.
72+
2. Creates an object to use when calculating the result value.
73+
3. Accesses the object's properties.
74+
4. Prints the result.
75+
5. Calls the function. This is when the object is actually created.
7876

77+
### `object` Declaration
7978

80-
You can have also **object declaration**: is not an expression, and cannot be used in a variable assignment, must be used directly:
79+
You can also use the `object` **declaration**. It isn't an expression, and can't be used in a variable assignment. You should use it to directly access its members:
8180

8281
<div class="language-kotlin" theme="idea" data-min-compiler-version="1.3">
8382

@@ -88,7 +87,6 @@ object DoAuth { //1
8887
}
8988
}
9089

91-
9290
fun main(){
9391
DoAuth.takeParams("foo", "qwerty") //3
9492
}
@@ -97,39 +95,37 @@ fun main(){
9795

9896
</div>
9997

100-
1. create object declaration
101-
2. define method
102-
3. use the object (initialization), calling method
98+
1. Creates an object declaration.
99+
2. Defines the object method.
100+
3. Calls the method. This is when the object is actually created.
103101

102+
### Companion Objects
104103

105-
106-
107-
An object declaration, inside a class, defines another useful case: the **companion object**.
108-
Syntactically similar to the static methods in Java, you call object's members using the *class* as qualifier.
109-
In Kotlin, before defining a companion object, decide whether it is better to write a simple *package-level* function.
104+
An object declaration inside a class defines another useful case: the **companion object**.
105+
Syntactically it's similar to the static methods in Java: you call object members using its *class name* as a qualifier.
106+
If you plan to use a companion object in Kotlin, consider using a *package-level* function instead.
110107

111108
<div class="language-kotlin" theme="idea" data-min-compiler-version="1.3">
112109

113110
```kotlin
114111
class BigBen { //1
115-
companion object Bonger{ //2
116-
fun getBongs(nTimes: Int){ //3
117-
for (i in 1 .. nTimes){
112+
companion object Bonger { //2
113+
fun getBongs(nTimes: Int) { //3
114+
for (i in 1 .. nTimes) {
118115
print("BONG ")
119116
}
120117
}
121118
}
122119
}
123120

124-
125-
fun main(){
121+
fun main() {
126122
BigBen.getBongs(12) //4
127123
}
128124
```
129125

130126
</div>
131127

132-
1. class definition, companion initialization
133-
2. companion definition - name can be omitted
134-
3. method definition
135-
4. accessing companion object
128+
1. Defines a class.
129+
2. Defines a companion. Its name can be omitted.
130+
3. Defines a companion object method.
131+
4. Calls the companion object method via the class name.

0 commit comments

Comments
 (0)