+51
Kotlin/Classes.org
+51
Kotlin/Classes.org
···
1
+
* Data classes
2
+
3
+
Kotlin has *data classes* which have the same functionality as classes,
4
+
but they come automatically with addtional member functions.
5
+
These members functions allow you to easily print the instance to readable output,
6
+
compare instances of a class, copy instances and more.
7
+
8
+
To declare a data class, use the keyword =data=:
9
+
10
+
#+begin_src kotlin
11
+
data class User(val name: String, val id: Int)
12
+
#+end_src
13
+
14
+
The most useful predefined member functions of data classes are:
15
+
16
+
| Function | Description |
17
+
|---------------+-----------------------------------------------------------------------------------------|
18
+
| =.toString()= | Prints a readable string of the class instance and its properties |
19
+
| =.equals()= | Compares instances of a class |
20
+
| =.copy()= | Creates a class instance by copying another, potentially with some different properties |
21
+
22
+
#+begin_src kotlin
23
+
import kotlin.random.Random
24
+
25
+
data class Employee(val name: String, var salary: Int)
26
+
27
+
class RandomEmployeeGenerator(var minSalary: Int, var maxSalary: Int) {
28
+
val names = listOf("John", "Mary", "Ann", "Paul", "Jack", "Elizabeth")
29
+
30
+
fun generateEmployee(): Employee {
31
+
val name = names.random()
32
+
val salary = Random.nextInt(from = minSalary, until = maxSalary)
33
+
34
+
return Employee(name, salary)
35
+
}
36
+
}
37
+
38
+
val empGen = RandomEmployeeGenerator(10, 30)
39
+
println(empGen.generateEmployee())
40
+
println(empGen.generateEmployee())
41
+
println(empGen.generateEmployee())
42
+
empGen.minSalary = 50
43
+
empGen.maxSalary = 100
44
+
println(empGen.generateEmployee())
45
+
#+end_src
46
+
47
+
#+RESULTS:
48
+
: Employee(name=Paul, salary=12)
49
+
: Employee(name=John, salary=22)
50
+
: Employee(name=Ann, salary=13)
51
+
: Employee(name=Jack, salary=74)