Kotlin
Notes for Professionals
Kotlin®
Notes for Professionals
80+ pages
of professional hints and tricks
GoalKicker.com
Free Programming Books
Disclaimer
This is an unocial free book created for educational purposes and is
not aliated with ocial Kotlin® group(s) or company(s).
All trademarks and registered trademarks are
the property of their respective owners
Contents
About
...................................................................................................................................................................................
1
Chapter 1: Getting started with Kotlin
...............................................................................................................
2
.................................................................................................................................................
Section 1.1: Hello World
Section 1.2: Hello World using a Companion Object
Section 1.3: Hello World using an Object Declaration
Section 1.4: Main methods using varargs
Section 1.5: Compile and Run Kotlin Code in Command Line
Section 1.6: Reading input from Command Line
..................................................................................................
................................................................................................
....................................................................................................................
...................................................................................
4
........................................................................................................
4
Chapter 2: Basics of Kotlin
Section 2.1: Basic examples
.......................................................................................................................................
6
..........................................................................................................................................
6
Chapter 3: Strings
.........................................................................................................................................................
7
Section 3.1: String Equality
Section 3.2: String Literals
Section 3.3: Elements of String
Section 3.4: String Templates
............................................................................................................................................
............................................................................................................................................
.....................................................................................................................................
8
.......................................................................................................................................
8
Chapter 4: Arrays
.........................................................................................................................................................
9
Section 4.1: Generic Arrays
Section 4.2: Arrays of Primitives
Section 4.3: Create an array
Section 4.4: Create an array using a closure
Section 4.5: Create an uninitialized array
Section 4.6: Extensions
Section 4.7: Iterate Array
...........................................................................................................................................
..................................................................................................................................
........................................................................................................................................
.............................................................................................................
9
...................................................................................................................
9
................................................................................................................................................
............................................................................................................................................
Chapter 5: Collections
Section 5.1: Using list
Section 5.2: Using map
Section 5.3: Using set
..............................................................................................................................................
11
...................................................................................................................................................
...............................................................................................................................................
..................................................................................................................................................
Chapter 6: Enum
..........................................................................................................................................................
12
Section 6.1: Initialization
Section 6.2: Functions and Properties in enums
Section 6.3: Simple enum
Section 6.4: Mutability
Chapter 7: Functions
..............................................................................................................................................
12
......................................................................................................
12
............................................................................................................................................
.................................................................................................................................................
.................................................................................................................................................
Section 7.1: Function References
Section 7.2: Basic Functions
Section 7.3: Inline Functions
Section 7.4: Lambda Functions
Section 7.5: Operator functions
Section 7.6: Functions Taking Other Functions
Section 7.7: Shorthand Functions
...............................................................................................................................
.......................................................................................................................................
.......................................................................................................................................
..................................................................................................................................
.................................................................................................................................
........................................................................................................
17
..............................................................................................................................
Chapter 8: Vararg Parameters in Functions
Section 8.1: Basics: Using the vararg keyword
Section 8.2: Spread Operator: Passing arrays into vararg functions
................................................................................................
.........................................................................................................
....................................................................
18
Chapter 9: Conditional Statements
...................................................................................................................
19
Section 9.1: When-statement argument matching
Section 9.2: When-statement as expression
..................................................................................................
19
............................................................................................................
19
2
2
3
4
7
7
9
9
9
10
10
11
11
Advertisement
11
12
12
14
14
15
16
16
16
17
18
18
Section 9.3: Standard if-statement
Section 9.4: If-statement as an expression
Section 9.5: When-statement instead of if-else-if chains
Section 9.6: When-statement with enums
............................................................................................................................
...............................................................................................................
.......................................................................................
20
................................................................................................................
20
Chapter 10: Loops in Kotlin
....................................................................................................................................
22
Section 10.1: Looping over iterables
Section 10.2: Repeat an action x times
Section 10.3: Break and continue
Section 10.4: Iterating over a Map in kotlin
Section 10.5: Recursion
Section 10.6: While Loops
Section 10.7: Functional constructs for iteration
...........................................................................................................................
......................................................................................................................
...............................................................................................................................
...............................................................................................................
...............................................................................................................................................
...........................................................................................................................................
......................................................................................................
23
Chapter 11: Ranges
.....................................................................................................................................................
25
Section 11.1: Integral Type Ranges
Section 11.2: downTo() function
Section 11.3: step() function
Section 11.4: until function
.............................................................................................................................
25
..................................................................................................................................
........................................................................................................................................
...........................................................................................................................................
Chapter 12: Regex
.......................................................................................................................................................
26
Section 12.1: Idioms for Regex Matching in When Expression
Section 12.2: Introduction to regular expressions in Kotlin
................................................................................
26
.....................................................................................
27
Chapter 13: Basic Lambdas
....................................................................................................................................
30
..............................................................................................
30
.........................................................................................
30
..............................................................................................................
Section 13.1: Lambda as parameter to filter function
Section 13.2: Lambda for benchmarking a function call
Section 13.3: Lambda passed as a variable
Chapter 14: Null Safety
Section 14.1: Smart casts
Section 14.2: Assertion
Section 14.3: Eliminate nulls from an Iterable and array
Section 14.4: Null Coalescing / Elvis Operator
Section 14.5: Nullable and Non-Nullable types
Section 14.6: Elvis Operator (?:)
Section 14.7: Safe call operator
Chapter 15: Class Delegation
...........................................................................................................................................
.............................................................................................................................................
.................................................................................................................................................
.........................................................................................
31
..........................................................................................................
.........................................................................................................
..................................................................................................................................
..................................................................................................................................
................................................................................................................................
Section 15.1: Delegate a method to another class
...................................................................................................
34
Chapter 16: Class Inheritance
...............................................................................................................................
35
Section 16.1: Basics: the 'open' keyword
Section 16.2: Inheriting fields from a class
Section 16.3: Inheriting methods from a class
Section 16.4: Overriding properties and methods
....................................................................................................................
................................................................................................................
..........................................................................................................
....................................................................................................
36
Chapter 17: Visibility Modifiers
.............................................................................................................................
38
Section 17.1: Code Sample
...........................................................................................................................................
38
Chapter 18: Generics
.................................................................................................................................................
39
Section 18.1: Declaration-site variance
Section 18.2: Use-site variance
......................................................................................................................
39
...................................................................................................................................
39
Chapter 19: Interfaces
..............................................................................................................................................
41
Section 19.1: Interface with default implementations
Section 19.2: Properties in Interfaces
Section 19.3: super keyword
Section 19.4: Basic Interface
.........................................................................................................................
.......................................................................................................................................
.......................................................................................................................................
...............................................................................................
41
19
19
22
22
22
23
23
Advertisement
23
25
25
25
30
31
31
31
31
32
32
32
34
35
35
36
42
42
42
Section 19.5: Conflicts when Implementing Multiple Interfaces with Default Implementations
..........................
43
Chapter 20: Singleton objects
..............................................................................................................................
44
Section 20.1: Use as replacement of static methods/fields of java
Section 20.2: Use as a singleton
................................................................................................................................
44
.......................................................................
44
Chapter 21: coroutines
.............................................................................................................................................
45
Section 21.1: Simple coroutine which delay's 1 second but not blocks
...................................................................
45
Chapter 22: Annotations
.........................................................................................................................................
46
Section 22.1: Meta-annotations
Section 22.2: Declaring an annotation
..................................................................................................................................
46
......................................................................................................................
46
Chapter 23: Type aliases
Section 23.1: Function type
Section 23.2: Generic type
.........................................................................................................................................
47
.........................................................................................................................................
..........................................................................................................................................
Chapter 24: Type-Safe Builders
.........................................................................................................................
48
Section 24.1: Type-safe tree structure builder
..........................................................................................................
48
.....................................................................................................................
Chapter 25: Delegated properties
Section 25.1: Observable properties
Section 25.2: Custom delegation
Section 25.3: Lazy initialization
Section 25.4: Map-backed properties
Section 25.5: Delegate Can be used as a layer to reduce boilerplate
..........................................................................................................................
...............................................................................................................................
..................................................................................................................................
.......................................................................................................................
..................................................................
49
Chapter 26: Reflection
.............................................................................................................................................
51
Section 26.1: Referencing a class
Section 26.2: Inter-operating with Java reflection
Section 26.3: Referencing a function
Section 26.4: Getting values of all properties of a class
Section 26.5: Setting values of all properties of a class
...............................................................................................................................
..................................................................................................
.........................................................................................................................
.........................................................................................
51
..........................................................................................
52
Chapter 27: Extension Methods
...........................................................................................................................
54
..........................................................................
...........................................................................................................................
Section 27.1: Potential Pitfall: Extensions are Resolved Statically
Section 27.2: Top-Level Extensions
Section 27.3: Lazy extension property workaround
Section 27.4: Sample extending Java 7+ Path class
Section 27.5: Sample extending long to render a human readable string
Section 27.6: Sample extending Java 8 Temporal classes to render an ISO formatted string
Section 27.7: Using extension functions to improve readability
Section 27.8: Extension functions to Companion Objects (appearance of Static functions)
Section 27.9: Extensions for easier reference View from code
.............................................................................
..............................
..............................................................................
................................................................................................
...............................................................................................
...........................................................
..........................
55
Chapter 28: DSL Building
........................................................................................................................................
58
Section 28.1: Infix approach to build DSL
Section 28.2: Using operators with lambdas
Section 28.3: Overriding invoke method to build DSL
Section 28.4: Using extensions with lambdas
..................................................................................................................
............................................................................................................
.............................................................................................
58
...........................................................................................................
58
Chapter 29: Idioms
.....................................................................................................................................................
60
.........................................................................................
60
Section 29.1: Serializable and serialVersionUid in Kotlin
Section 29.2: Delegate to a class without providing it in the public constructor
Section 29.3: Use let or also to simplify working with nullable objects
Section 29.4: Use apply to initialize objects or to achieve method chaining
Section 29.5: Fluent methods in Kotlin
Section 29.6: Filtering a list
Section 29.7: Creating DTOs (POJOs/POCOs)
......................................................................................................................
.........................................................................................................................................
........................................................................................................
..................................................
60
.................................................................
Advertisement
........................................................
47
47
49
49
49
49
49
51
51
51
54
54
54
55
55
55
56
57
58
58
61
61
61
62
62
Chapter 30: RecyclerView in Kotlin
Section 30.1: Main class and Adapter
...................................................................................................................
63
........................................................................................................................
63
Chapter 31: logging in kotlin
Section 31.1: kotlin.logging
Chapter 32: Exceptions
..................................................................................................................................
65
..........................................................................................................................................
.............................................................................................................................................
Section 32.1: Catching exception with try-catch-finally
...........................................................................................
66
Chapter 33: JUnit
Section 33.1: Rules
........................................................................................................................................................
67
........................................................................................................................................................
67
Chapter 34: Kotlin Android Extensions
............................................................................................................
68
Section 34.1: Using Views
Section 34.2: Configuration
Section 34.3: Painful listener for getting notice, when the view is completely drawn now is so simple and
............................................................................................................................................
........................................................................................................................................
68
68
awesome with Kotlin's extension
.......................................................................................................................
69
Section 34.4: Product flavors
.....................................................................................................................................
69
Chapter 35: Kotlin for Java Developers
.........................................................................................................
71
Section 35.1: Declaring Variables
Section 35.2: Quick Facts
Section 35.3: Equality & Identity
Section 35.4: IF, TRY and others are expressions, not statements
............................................................................................................................................
.................................................................................................................................
...............................................................................................................................
.........................................................................
72
Chapter 36: Java 8 Stream Equivalents
Section 36.1: Accumulate names in a List
Section 36.2: Collect example #5 - find people of legal age, output formatted string
Section 36.3: Collect example #6 - group people by age, print age and names together
Section 36.4: Dierent Kinds of Streams #7 - lazily iterate Doubles, map to Int, map to String, print each
.................................................................................................................
.........................................................................................................
........................................
.................................
73
73
73
73
................................................................................................................................................................................
74
...............................
.....................................................................................
..............................................................................................
......................................................................................................
Section 36.5: Counting items in a list after filter is applied
Section 36.6: Convert elements to strings and concatenate them, separated by commas
Section 36.7: Compute sum of salaries of employee
Section 36.8: Group employees by department
Section 36.9: Compute sum of salaries by department
Section 36.10: Partition students into passing and failing
Section 36.11: Names of male members
Section 36.12: Group names of members in roster by gender
Section 36.13: Filter a list to another list
Section 36.14: Finding shortest string a list
Section 36.15: Dierent Kinds of Streams #2 - lazily using first item if exists
Section 36.16: Dierent Kinds of Streams #3 - iterate a range of Integers
Section 36.17: Dierent Kinds of Streams #4 - iterate an array, map the values, calculate the average
..........................................................................................
.......................................................................................
.......................................................
..........................................................
....................................................................................................................
...................................................................................................................
...............................................................................................................
...............................................................................
................................................................................................................................................................................
77
Section 36.18: Dierent Kinds of Streams #5 - lazily iterate a list of strings, map the values, convert to Int,
find max
...............................................................................................................................................................
77
Section 36.19: Dierent Kinds of Streams #6 - lazily iterate a stream of Ints, map the values, print results
................................................................................................................................................................................
77
Section 36.20: How streams work - filter, upper case, then sort a list
Section 36.21: Dierent Kinds of Streams #1 - eager using first item if it exists
Section 36.22: Collect example #7a - Map names, join together with delimiter
Section 36.23: Collect example #7b - Collect with SummarizingInt
...................................................................
...................................................
...................................................
78
.......................................................................
79
65
66
71
71
71
Advertisement
75
75
75
75
75
75
76
76
76
76
76
77
78
78
Chapter 37: Kotlin Caveats
....................................................................................................................................
81
Section 37.1: Calling a toString() on a nullable type
................................................................................................
81
Appendix A: Configuring Kotlin build
................................................................................................................
82
Section A.1: Gradle configuration
Section A.2: Using Android Studio
Section A.3: Migrating from Gradle using Groovy script to Kotlin script
...............................................................................................................................
.............................................................................................................................
...............................................................
84
82
83
Credits
..............................................................................................................................................................................
86
You may also like
........................................................................................................................................................
88
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
https://goalkicker.com/KotlinBook
This Kotlin® Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official Kotlin® group(s) or company(s) nor Stack Overflow. All
trademarks and registered trademarks are the property of their respective
company owners
The information presented in this book is not guaranteed to be correct nor
accurate, use at your own risk
Please send feedback and corrections to [email protected]
GoalKicker.com – Kotlin® Notes for Professionals
1
Chapter 1: Getting started with Kotlin
Version Release Date
1.0.0
2016-02-15
1.0.1
1.0.2
1.0.3
1.0.4
1.0.5
1.0.6
1.1.0
1.1.1
1.1.2
1.1.3
1.1.6
1.2.2
1.2.3
1.2.4
2016-03-16
2016-05-13
2016-06-30
2016-09-22
2016-11-08
2016-12-27
2017-03-01
2017-03-14
2017-04-25
2017-06-23
2017-11-13
2018-01-17
2018-03-01
2018-04-19
Section 1.1: Hello World
All Kotlin programs start at the main function. Here is an example of a simple Kotlin "Hello World" program:
package my.program
fun main(args: Array<String>) {
println("Hello, world!")
}
Place the above code into a file named Main.kt (this filename is entirely arbitrary)
When targeting the JVM, the function will be compiled as a static method in a class with a name derived from the
filename. In the above example, the main class to run would be my.program.MainKt.
To change the name of the class that contains top-level functions for a particular file, place the following annotation
at the top of the file above the package statement:
@file:JvmName("MyApp")
In this example, the main class to run would now be my.program.MyApp.
See also:
Package level functions including @JvmName annotation.
Annotation use-site targets
Section 1.2: Hello World using a Companion Object
Similar to using an Object Declaration, you can define the main function of a Kotlin program using a Companion
Object of a class.
GoalKicker.com – Kotlin® Notes for Professionals
2
package my.program
class App {
companion object {
@JvmStatic fun main(args: Array<String>) {
println("Hello World")
}
}
}
The class name that you will run is the name of your class, in this case is my.program.App.
The advantage to this method over a top-level function is that the class name to run is more self-evident, and any
other functions you add are scoped into the class App. This is similar to the Object Declaration example, other
than you are in control of instantiating any classes to do further work.
A slight variation that instantiates the class to do the actual "hello":
class App {
companion object {
@JvmStatic fun main(args: Array<String>) {
App().run()
}
}
fun run() {
println("Hello World")
}
}
See also:
Static Methods including the @JvmStatic annotation
Section 1.3: Hello World using an Object Declaration
You can alternatively use an Object Declaration that contains the main function for a Kotlin program.
package my.program
object App {
@JvmSta...