Android Programming With Kotlin For Professionals Guide To Kotlin Programming Notes For Professionals Step by Step
Android Programming With Kotlin For Professionals Guide To Kotlin Programming Notes For Professionals Step by Step
About
......................................................................................
......................................................................................
....... 1 Chapter 1: Getting started with Kotlin
......................................................................................
......................... 2
Section 1.1: Hello World
...............................................................................................................
.................................. 2
Section 1.2: Hello World using a Companion Object
.................................................................................................. 2
Section 1.3: Hello World using an Object Declaration
................................................................................................ 3
Section 1.4: Main methods using varargs
...............................................................................................................
..... 4
Section 1.5: Compile and Run Kotlin Code in Command Line
................................................................................... 4
Section 1.6: Reading input from Command Line
........................................................................................................ 4
Chapter 4: Arrays
......................................................................................
................................................................... 9
Section 4.1: Generic Arrays
...............................................................................................................
............................ 9
Section 4.2: Arrays of Primitives
...............................................................................................................
................... 9
Section 4.3: Create an array
...............................................................................................................
......................... 9
Section 4.4: Create an array using a closure
.............................................................................................................
9
Section 4.5: Create an uninitialized array
...............................................................................................................
.... 9
Section 4.6: Extensions
...............................................................................................................
................................. 10
Section 4.7: Iterate Array
...............................................................................................................
............................. 10
Chapter 5: Collections
......................................................................................
........................................................ 11
Section 5.1: Using list
...............................................................................................................
.................................... 11
Section 5.2: Using map
...............................................................................................................
................................ 11
Section 5.3: Using set
...............................................................................................................
................................... 11
Chapter 6: Enum
......................................................................................
.................................................................... 12
Section 6.1: Initialization
...............................................................................................................
............................... 12
Section 6.2: Functions and Properties in enums
...................................................................................................... 12
Section 6.3: Simple enum
...............................................................................................................
............................. 12
Section 6.4: Mutability
...............................................................................................................
.................................. 12
Chapter 7: Functions
......................................................................................
........................................................... 14
Section 7.1: Function References
...............................................................................................................
................ 14
Section 7.2: Basic Functions
...............................................................................................................
........................ 15
Section 7.3: Inline Functions
...............................................................................................................
........................ 16
Section 7.4: Lambda Functions
...............................................................................................................
................... 16
Section 7.5: Operator functions
...............................................................................................................
.................. 16
Section 7.6: Functions Taking Other Functions
........................................................................................................ 17
Section 7.7: Shorthand Functions
...............................................................................................................
............... 17
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 web@petercv.com
Chapter 1: Getting started with
Kotlin
Version Release Date
1.0.0 2016-02-15
1.0.1 2016-03-16
1.0.2 2016-05-13
1.0.3 2016-06-30
1.0.4 2016-09-22
1.0.5 2016-11-08
1.0.6 2016-12-27
1.1.0 2017-03-01
1.1.1 2017-03-14
1.1.2 2017-04-25
1.1.3 2017-06-23
1.1.6 2017-11-13
1.2.2 2018-01-17
1.2.3 2018-03-01
1.2.4 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
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.
package my.program
class App {
companion object {
The class name that you will run is the name of your class, in this
case is my.program .App .
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 {
The class name that you will run is the name of your object, in this
case is my.program .App .
} else {
println( "The value of b is $b" ) b
}
return max;
}
Here, Enter two number from the command line to find the maximum
number. Output:
Enter Two number
71 89 // Enter two number from command line
The value of b is 89 Max number is: 89
For !! Operator Please check Null Safety . Note: Above example
compile and run on Intellij.
Chapter 2: Basics of Kotlin
This topic covers the basics of Kotlin for beginners.
Section 2.1: Basic examples
1. The Unit return type declaration is optional for functions. The
following codes are equivalent.
fun printHello( name: String ?): Unit {
if ( name != null )
println( "Hello ${name}" )
}
In java :
int num= 10
String s = "i =" + i;
In Kotlin
val num = 10
val s = "i = $num"
"""
Leading whitespace can be removed with trimMargin() function.
val i = 10
val s = "i = $i" // evaluates to "i = 10"
Or an arbitrary expression in curly braces:
val s = "abc"
val str = "$s.length is ${s.length}" // evaluates to "abc.length is 3"
To include a literal dollar sign in a string, escape it using a backslash:
val str = " \$ foo" // evaluates to "$foo"
The exception is raw strings, which do not support escaping. In raw
strings you can use the following syntax to represent a dollar sign.
var strings = Array< String>( size = 5 , init = { index -> "Item #$index"
})
print( Arrays .toString ( a)) // prints "[Item #0, Item #1, Item #2, Item
#3, Item #4]" print( a.size ) // prints 5
Arrays have get ( index: Int ): T and set ( index: Int , value: T)
functions:
strings.set ( 2 , "ChangedItem" )
print( strings.get ( 2 )) // prints "ChangedItem"
}
Section 6.2: Functions and Properties
in enums
Enum classes can also declare members (i.e. properties and
functions). A semicolon (;) must be placed between the last enum
object and the first member declaration.
If a member is abstract , the enum objects must implement it.
enum class Color {
RED {
override val rgb: Int = 0xFF0000
},
GREEN {
override val rgb: Int = 0x00FF00
},
BLUE {
override val rgb: Int = 0x0000FF
}
;
abstract val rgb: Int
fun colorString() = "#%06X" .format ( 0xFFFFFF and rgb)
}
Section 6.3: Simple enum
enum class Color {
RED, GREEN, BLUE
}
Each enum constant is an object. Enum constants are separated with
commas.
Section 6.4: Mutability
Enums can be mutable, this is another way to obtain a singleton
behavior:
fun foo( p0: Foo0, p1: Foo1, p2: Foo2): Bar { //...
}
println(:: foo:: class .java .genericInterfaces [ 0 ])
// kotlin.jvm.functions.Function3<Foo0, Foo1, Foo2, Bar>
// Human readable type: (Foo0, Foo1, Foo2) -> Bar
//...
}
val ref = Foo:: foo
println( ref:: class .java .genericInterfaces [ 0 ])
// kotlin.jvm.functions.Function4<Foo, Foo0, Foo1, Foo2, Bar>
// Human readable type: (Foo, Foo0, Foo1, Foo2) -> Bar
// takes 4 parameters, with receiver as first and actual parameters
following, in their order
class Bar {
fun bar()
}
print( Bar:: bar) // works on member functions, too.
//...
}
val ref = Foo:: foo
println( ref:: class .java .genericInterfaces [ 0 ]) //
kotlin.jvm.functions.Function3<Foo0, Foo1, Foo2, Bar> // Human
readable type: (Foo0, Foo1, Foo2) -> Bar // takes 3 parameters,
receiver not needed
object Bar {
fun bar()
}
print( Bar:: bar) // works on member functions, too.
}
Note this example is given only to show how bounded function
reference works. It's bad practice in all other senses.
There is a special case, though. An extension function declared as a
member can't be referenced.
class Foo
class Bar {
fun Foo.foo () {}
val ref = Foo:: foo // compile error }
Section 7.2: Basic Functions
Functions are declared using the fun keyword, followed by a function
name and any parameters. You can also specify the return type of a
function, which defaults to Unit . The body of the function is enclosed
in braces {}. If the return type is other than Unit , the body must issue
a return statement for every terminating branch within the body.
fun main() {
val name = "Foo"
sayMyName() # => Unresolved reference: name
}
Section 7.4: Lambda Functions
Lambda functions are anonymous functions which are usually
created during a function call to act as a function parameter. They are
declared by surrounding expressions with {braces} - if arguments are
needed, these are put before an arrow -> .
If the lambda function only needs one argument, then the argument
list can be omitted and the single argument be referred to using it
instead.
{ "Your name is $it" }
If the only argument to a function is a lambda function, then
parentheses can be completely omitted from the function call.
fun main() {
twice {
println( "Foo" ) } # => Foo
# => Foo
}
Section 7.7: Shorthand Functions
If a function contains just one expression, we can omit the brace
brackets and use an equals instead, like a variable assignment. The
result of the expression is returned automatically.
fun sayMyName( name: String ): String = "Your name is $name"
Chapter 8: Vararg Parameters in
Functions
Section 8.1: Basics: Using the vararg
keyword
Define the function using the vararg keyword.
fun printNumbers( vararg numbers: Int ) {
for ( number in numbers) {
println( number)
}
}
Now you can pass as many parameters (of the correct type) into the
function as you want.
printNumbers( 0 , 1 ) // Prints "0" "1"
printNumbers( 10 , 20 , 30 , 500 ) // Prints "10" "20" "30" "500"
Notes: Vararg parameters must be the last parameter in the
parameter list.
Section 8.2: Spread Operator: Passing
arrays into vararg functions
Arrays can be passed into vararg functions using the Spread
Operator , *.
Assuming the following function exists...
fun printNumbers( vararg numbers: Int ) {
for ( number in numbers) {
println( number)
}
}
You can pass an array into the function like so...
val numbers = intArrayOf( 1 , 2 , 3 ) printNumbers(* numbers)
// This is the same as passing in (1, 2, 3)
The spread operator can also be used in the middle of the
parameters...
val numbers = intArrayOf( 1 , 2 , 3 ) printNumbers( 10 , 20 , *
numbers, 30 , 40 ) // This is the same as passing in (10, 20, 1, 2, 3,
30, 40)
Chapter 9: Conditional
Statements
Section 9.1: When-statement argument
matching
When given an argument, the when -statement matches the
argument against the branches in sequence. The matching is done
using the == operator which performs null checks and compares the
operands using the equals function. The first matching one will be
executed.
when ( x) {
"English" -> print( "How are you?" )
"German" -> print( "Wie geht es dir?" )
else -> print( "I don't know that language yet :(" )
}
The when statement also knows some more advanced matching
options:
}
print( greeting)
To be used as an expression, the when-statement must be
exhaustive, i.e. either have an else branch or cover all possibilities
with the branches in another way.
Section 9.3: Standard if-statement
val str = "Hello!"
if ( str.length == 0 ) {
print( "The string is empty!" )
TIP: Kotlin can infer the type of the variable for you but if you want to
be sure of the type just annotate it on the variable like: val str: String
= this will enforce the type and will make it easier to read.
Section 9.5: When-statement instead
of if-else-if chains
The when-statement is an alternative to an if-statement with multiple
else-if-branches:
when {
str.length == 0 -> print( "The string is empty!" )
str.length > 5 -> print( "The string is short!" )
else -> print( "The string is long!" )
}
Same code written using an if-else-if chain:
if ( str.length == 0 ) {
print( "The string is empty!" )
} else if ( str.length > 5 ) { print( "The string is short!" )
} else {
print( "The string is long!" )
}
Just like with the if-statement, the else-branch is optional, and you
can add as many or as few branches as you like. You can also have
multiline-branches:
when {
condition -> {
doSomething()
doSomeMore()
}
else -> doSomethingElse() }
Section 9.6: When-statement with
enums
when can be used to match enum values:
}
}
As you can see in second case line (Monday and Tuesday) it is also
possible to combine two or more enum values.
If your cases are not exhaustive the compile will show an error. You
can use else to handle default cases:
}
}
Though the same can be done using if- then- else construct, when
takes care of missing enum values and makes it more natural.
Check here for more information about kotlin enum
Chapter 10: Loops in Kotlin
Section 10.1: Looping over iterables
You can loop over any iterable by using the standard for-loop:
}
Lots of things in Kotlin are iterable, like number ranges:
for ( i in 0 ..9 ) {
print( i)
}
iterable. forEach {
print( it.toString ())
}
}
Section 10.3: Break and continue
Break and continue keywords work like they do in other languages.
while ( true ) {
if ( condition1) {
continue // Will immediately start the next iteration, without executing
the rest of the
loop body
}
if ( condition2) {
}
}
This approach won't work for the functional forEach construct,
though.
Section 10.4: Iterating over a Map in
kotlin
//iterates over a map, getting the key and value at once
var map = hashMapOf( 1 to "foo" , 2 to "bar" , 3 to "baz" )
while ( condition) {
doSomething()
}
do {
doSomething()
} while ( condition)
In the do-while loop, the condition block has access to values and
variables declared in the loop body.
Section 10.7: Functional constructs for
iteration
The Kotlin Standard Library also provides numerous useful functions
to iteratively work upon collections.
For example, the map function can be used to transform a list of
items.
val numbers = listOf( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 0 )
val numberStrings = numbers.map { "Number $it" }
Uses less horizontal space but more vertical space than the
"anonymous temporaries" template. Preferable over the "anonymous
temporaries" template if the when expression is in a loop--in that
case, regex definitions should be placed outside the loop.
import kotlin.text.regex
var string = /* some string */
when {
regex1.matches ( string) -> /* do stuff */
regex2.matches ( string) -> /* do stuff */
/* etc */
}
Using anonymous temporaries:
Uses less vertical space but more horizontal space than the
"immutable locals" template. Should not be used if then when
expression is in a loop.
import kotlin.text.regex
var string = /* some string */
when {
Regex( /* pattern */ ) .matches ( string) -> /* do stuff */ Regex( /*
pattern */ ) .matches ( string) -> /* do stuff */ /* etc */
}
Using the visitor pattern:
Has the benefit of closely emulating the "argument-ful" when syntax.
This is beneficial because it more clearly indicates the argument of
the when expression, and also precludes certain programmer
mistakes that could arise from having to repeat the when argument in
every whenEntry. Either the "immutable locals" or the "anonymous
temporaries" template may be used with this implementation the
visitor pattern.
import kotlin.text.regex
var string = /* some string */
And the minimal definition of the wrapper class for the when
expression argument:
}
Section 12.2: Introduction to regular
expressions in Kotlin
This post shows how to use most of the functions in the Regex class,
work with null safely related to the Regex functions, and how raw
strings makes it easier to write and read regex patterns.
The RegEx class
To work with regular expressions in Kotlin, you need to use the
Regex( pattern: String ) class and invoke functions like find( ..) or
replace( ..) on that regex object.
An example on how to use the Regex class that returns true if the
input string contains c or d:
val regex = Regex( pattern = "c|d" )
val matched = regex.containsMatchIn ( input = "abc" ) // matched:
true
The essential thing to understand with all the Regex functions is that
the result is based on matching the regex pattern and the input string.
Some of the functions requires a full match, while the rest requires
only a partial match. The containsMatchIn( ..) function used in the
example requires a partial match and is explained later in this post.
The input string will be matched against the pattern in the Regex
object. It returns a Matchresult? object with the first matched text after
the startIndex, or null if the pattern didn't match the input string. The
result string is retrieved from the MatchResult? object's value
property. The startIndex parameter is optional with the default value
0.
To extract the first valid phone number from a string with contact
details:
val phoneNumber : String ? = Regex( pattern = """ \d {3} \d {3} \d
{4}""" ) .find ( input = "phone: 123-456-7890, e.." )? .value //
phoneNumber: 123-456-7890
With no valid phone number in the input string, the variable
phoneNumber will be null .
findAll(input: CharSequence, startIndex: Int): Sequence
Returns all the matches from the input string that matches the regex
pattern.
To print out all numbers separated with space, from a text with letters
and digits:
object Benchmark {
fun realtime( body: () -> Unit ): Duration {
val start = Instant.now ()
try {
body ()
} finally {
val end = Instant.now ()
return Duration.between ( start, end)
}
}
}
Usage:
obj ? .apply {
foo()
bar()
}
This will call foo and bar on obj (which is this in the apply block) only
if obj is non-null, skipping the entire block otherwise.
To bring a nullable variable into scope as a non-nullable reference
without making it the implicit receiver of function and property calls,
you can use let instead of apply:
}
notnull could be named anything, or even left out and used through
the implicit lambda parameter it.
Chapter 15: Class Delegation
A Kotlin class may implement an interface by delegating its methods
and properties to another object that implements that interface. This
provides a way to compose behavior using association rather than
inheritance.
Section 15.1: Delegate a method to
another class
interface Foo {
fun example()
}
class Bar {
fun example() {
println( "Hello, world!" )
}
}
class Baz( b : Bar) : Foo by b
Baz( Bar()) .example ()
The example prints Hello, world!
Chapter 16: Class Inheritance
Parameter Details
Base Class Class that is inherited from
Derived Class Class that inherits from Base Class
Init Arguments Arguments passed to constructor of Base Class
Function Definition Function in Derived Class that has different code
than the same in the Base Class DC-Object ”Derived Class-Object“
Object that has the type of the Derived Class
}
Section 16.3: Inheriting methods from
a class
Defining the base class:
open class Person {
fun jump() {
println( "Jumping..." )
}
}
Defining the derived class:
class Ninja: Person() {
fun sneak() {
println( "Sneaking around..." )
}
}
The Ninja has access to all of the methods in Person
}
Section 16.4: Overriding properties
and methods
Overriding properties (both read-only and mutable):
fun main( args: Array< String>) { val car: Car = BrokenCar( "Lada" )
car.speed = 10
}
Overriding methods:
}
object Titanic : Ship {
var canSail = true
A List can hold numbers, words or really anything. That's why we call
the List generic .
Generics are basically used to define which types a class can hold
and which type an object currently holds.
Section 18.1: Declaration-site variance
Declaration-site variance can be thought of as declaration of use-site
variance once and for all the use-sites.
class Consumer< in T> { fun consume( t: T) { ... } }
fun charSequencesConsumer() : Consumer< CharSequence>() = ...
val stringConsumer : Consumer< String> =
charSequenceConsumer() // OK since in-projection val anyConsumer
: Consumer< Any> = charSequenceConsumer() // Error, Any cannot
be passed
val outConsumer : Consumer< out CharSequence> = ... // Error, T is
`in`-parameter
Widespread examples of declaration-site variance are List< out T> ,
which is immutable so that T only appears as the return value type,
and Comparator< in T> , which only receives T as argument.
Section 18.2: Use-site variance
Use-site variance is similar to Java wildcards:
Out-projection:
val takeList : MutableList< out SomeType> = ... // Java: List<?
extends SomeType>
val takenValue : SomeType = takeList[ 0 ] // OK, since upper bound is
SomeType
takeList.add ( takenValue) // Error, lower bound for generic is not
specified
In-projection:
val putList : MutableList< in SomeType> = ... // Java: List<? super
SomeType>
val valueToPut : SomeType = ...
putList .add ( valueToPut) // OK, since lower bound is SomeType
putList[ 0 ] // This expression has type Any, since no upper bound is
specified
Star-projection
val starList : MutableList<*> = ... // Java: List<?>
starList[ 0 ] // This expression has type Any, since no upper bound is
specified starList.add ( someValue) // Error, lower bound for generic is
not specified
See also: Variant Generics interoperability when calling Kotlin from
Java.
Chapter 19: Interfaces
Section 19.1: Interface with default
implementations
An interface in Kotlin can have default implementations for functions:
interface MyInterface {
fun withImplementation() {
print( "withImplementation() was called" )
}
}
Classes implementing such interfaces will be able to use those
functions without reimplementing
Properties
Default implementations also work for property getters and setters:
interface MyInterface2 {
val helloWorld
get () = "Hello World!" }
Interface accessors implementations can't use backing fields
interface MyInterface3 {
// this property won't compile! var helloWorld: Int
get () = field
set ( value) { field = value } }
Multiple implementations
When multiple interfaces implement the same function, or all of them
define with one or more implementing, the derived class needs to
manually resolve proper call
interface A {
fun notImplemented()
fun implementedOnlyInA() { print( "only A" ) } fun
implementedInBoth() { print( "both, A" ) } fun implementedInOne() {
print( "implemented in A" ) }
interface B {
fun implementedInBoth() { print( "both, B" ) } fun
implementedInOne() // only defined
}
class MyClass: A, B {
override fun notImplemented() { print( "Normal implementation" ) }
// implementedOnlyInA() can by normally used in instances
fun foo() {
print( property)
}
}
}
}
If the method in the interface has its own default implementation, we
can use super keyword to access it. super .funcOne ()
Section 19.4: Basic Interface
A Kotlin interface contains declarations of abstract methods, and
default method implementations although they cannot store state.
interface MyInterface {
fun bar()
}
This interface can now be implemented by a class as follows:
class Child : MyInterface { override fun bar() {
print( "bar() was called" ) }
}
Section 19.5: Conflicts when
Implementing Multiple Interfaces with
Default Implementations
When implementing more than one interface that have methods of
the same name that include default implementations, it is ambiguous
to the compiler which implementation should be used. In the case of
a conflict, the developer must override the conflicting method and
provide a custom implementation. That implementation may choose
to delegate to the default implementations or not.
interface FirstTrait {
fun foo() { print( "first" ) } fun bar()
interface SecondTrait {
fun foo() { print( "second" ) } fun bar() { print( "bar" ) }
}
// function bar() only has a default implementation in one interface
and therefore is ok. }
Chapter 20: Singleton objects
An object is a special kind of class, which can be declared using
object keyword. Objects are similar to Singletons (a design pattern)
in java. It also functions as the static part of java. Beginners who are
switching from java to kotlin can vastly use this feature, in place of
static, or singletons.
Section 20.1: Use as replacement of
static methods/fields of java
object CommonUtils {
var anyname: String = "Hello"
From any other class, just invoke the variable and functions in this
way:
CommonUtils.anyname
CommonUtils.dispMsg ( "like static call" )
Section 20.2: Use as a singleton
Kotlin objects are actually just singletons. Its primary advantage is
that you don't have to use SomeSingleton.INSTANCE to get the
instance of the singleton.
In java your singleton looks like this:
}
In kotlin, the equivalent code is
object SharedRegistry {
fun register( key: String , thing: Object ) {}
}
}
It's obviously less verbose to use.
Chapter 21: coroutines
Examples of Kotlin's experimental(yet) implementation of coroutines
Section 21.1: Simple coroutine which
delay's 1 second but not blocks
(from official doc )
}
println( "Hello," ) // main function continues while coroutine is delayed
Thread .sleep ( 2000L) // block main thread for 2 seconds to keep
JVM alive
}
result
Hello, World!
Chapter 22: Annotations
Section 22.1: Meta-annotations
When declaring an annotation, meta-info can be included using the
following meta-annotations:
@Target: specifies the possible kinds of elements which can be
annotated with the annotation (classes, functions, properties,
expressions etc.)
@Retention specifies whether the annotation is stored in the
compiled class files and whether it's visible through reflection at
runtime (by default, both are true.)
@Repeatable allows using the same annotation on a single element
multiple times.
@MustBeDocumented specifies that the annotation is part of the
public API and should be included in the class or method signature
shown in the generated API documentation.
Example:
@Target( AnnotationTarget.CLASS , AnnotationTarget.FUNCTION ,
AnnotationTarget. VALUE_PARAMETER ,
AnnotationTarget.EXPRESSION ) @Retention(
AnnotationRetention.SOURCE )
@MustBeDocumented
annotation class Fancy
Section 22.2: Declaring an annotation
Annotations are means of attaching metadata to code. To declare an
annotation, put the annotation modifier in front of a class:
annotation class Strippable
Annotations can have meta-annotations:
@Target( AnnotationTarget.CLASS , AnnotationTarget.FUNCTION ,
AnnotationTarget.VALUE_PARAMETER ,
AnnotationTarget.EXPRESSION )
annotation class Strippable
Annotations, like other classes, can have constructors:
annotation class Strippable( val importanceValue: Int )
But unlike other classes, is limited to the following types:
types that correspond to Java primitive types (Int, Long etc.); strings
classes ( Foo:: class)
enums
other annotations
arrays of the types listed above
Chapter 23: Type aliases
With type aliases, we can give an alias to other type. It's ideal for
giving a name to function types like ( String ) -> Boolean or generic
type like Pair< Person, Person> .
Type aliases support generics. An alias can replace a type with
generics and an alias can be generics.
Section 23.1: Function type
typealias StringValidator = ( String ) -> Boolean
typealias Reductor< T, U, V> = ( T, U) -> V
Section 23.2: Generic type
typealias Parents = Pair< Person, Person>
typealias Accounts = List< Account>
Chapter 24: Type-Safe Builders
Section 24.1: Type-safe tree structure
builder
Builders can be defined as a set of extension functions taking lambda
expressions with receivers as arguments. In this example, a menu of
a JFrame is being built:
import javax.swing.*
fun JMenuBar .menu ( caption: String , init : JMenu .() -> Unit ) {
val menu = JMenu ( caption)
menu.init ()
add( menu)
fun JMenu .menuItem ( caption: String , init : JMenuItem .() -> Unit )
{
val menuItem = JMenuItem ( caption)
menuItem.init ()
add( menuItem)
}
These functions can then be used to build a tree structure of objects
in an easy way:
class MyFrame : JFrame () {
init {
menuBar {
menu( "Menu1" ) {
menuItem( "Item1" ) {
}
menu( "Menu2" ) {
menuItem( "Item3" ) {}
menuItem( "Item4" ) {}
}
}
}
Chapter 25: Delegated
properties
Kotlin can delegate the implementation of a property to a handler
object. Some standard handlers are included, such as lazy
initialization or observable properties. Custom handlers can also be
created.
Section 25.1: Observable properties
var foo : Int by Delegates.observable ( "1" ) { property, oldValue,
newValue ->
println( "${property.name} was changed from $oldValue to
$newValue" )
}
foo = 2
init {
reference = WeakReference ( this )
}
}
init {
reference = this
}
Chapter 26: Reflection
Reflection is a language's ability to inspect code at runtime instead of
compile time.
Section 26.1: Referencing a class
To obtain a reference to a KClass object representing some class use
double colons:
val c1 = String :: class
val c2 = MyClass:: class
Section 26.2: Inter-operating with Java
reflection
To obtain a Java's Class object from Kotlin's KClass use the .java
extension property:
val stringKClass: KClass< String> = String :: class
val c1: Class< String> = stringKClass.java
val c2: Class< MyClass> = MyClass:: class .java
The latter example will be optimized by the compiler to not allocate an
intermediate KClass instance.
Section 26.3: Referencing a function
Functions are first-class citizens in Kotlin. You can obtain a reference
on it using double colons and then pass it to another function:
fun isPositive( x: Int ) = x > 0
val numbers = listOf( 2 , - 1 , 0 , 1 , 2 )
println( numbers.filter (:: isPositive)) // [1, 2]
Section 26.4: Getting values of all
properties of a class
Given Example class extending BaseExample class with some
properties:
open class BaseExample( val baseField: String )
class Example( val field1: String , val field2: Int , baseField: String ):
BaseExample( baseField) {
val field3: String
get () = "Property without backing field"
val field4 by lazy { "Delegated value" }
private val privateField: String = "Private value"
}
One can get hold of all properties of a class:
val example = Example( field1 = "abc" , field2 = 1 , baseField =
"someText" )
example:: class .memberProperties .forEach { member ->
println( "${member.name} -> ${member.get(example)}" )
The helper function and it's usage might look like this:
}
Section 26.5: Setting values of all
properties of a class
As an example we want to set all string properties of a sample class
class TestClass {
val readOnlyProperty: String
get () = "Read only!"
callMyExtension( Sub())
The above example will print "Defined for Super" , because the
declared type of the variable myVar is Super.
Section 27.2: Top-Level Extensions
Top-level extension methods are not contained within a class.
}
}
Above an extension method is defined for the type IntArray. Note that
the object for which the extension method is defined (called the
receiver ) is accessed using the keyword this .
This extension can be called like so:
val myArray = intArrayOf( 1 , 2 , 3 )
intArrayOf( 4 , 5 , 6 ) .addTo ( myArray)
Section 27.3: Lazy extension property
workaround
Assume you want to create an extension property that is expensive to
compute. Thus you would like to cache the computation, by using the
lazy property delegate and refer to current instance (this ), but you
cannot do it, as explained in the Kotlin issues KT-9686 and KT-13053
. However, there is an official workaround provided here .
units[ digitGroups];
}
But the use of apply is not that clear as to your intent. Sometimes it is
clearer to create a similar extension function to in effect rename the
action and make it more self-evident. This should not be allowed to
get out of hand, but for very common actions such as verification:
infix inline fun < T: Any> T.verifiedWith ( verifyWith: T.() -> Unit ): T {
this .verifyWith ()
return this
}
You could now write the code as:
Which now let's people know what to expect within the lambda
parameter.
Note that the type parameter T for verifiedBy is same as T: Any ?
meaning that even nullable types will be able to use that version of
the extension. Although verifiedWith requires non-nullable.
Section 27.8: Extension functions to
Companion Objects (appearance of
Static functions)
If you want to extend a class as-if you are a static function, for
example for class Something add static looking function fromString,
this can only work if the class has a companion object and that the
extension function has been declared upon the companion object:
class Something {
companion object {}
}
class SomethingElse { }
fun Something.Companion .fromString ( s: String ): Something = ...
fun SomethingElse.fromString ( s: String ): SomethingElse = ...
fun main( args: Array< String>) {
Something.fromString ( "" ) //valid as extension function declared
upon the //companion object
SomethingElse() .fromString ( "" ) //valid, function invoked on instance
not //statically
SomethingElse.fromString ( "" ) //invalid }
Section 27.9: Extensions for easier
reference View from code
You can use extensions for reference View, no more boilerplate after
you created the views.
Original Idea is by Anko Library
Extensions
inline fun < reified T : View> View .find ( id: Int ): T = findViewById(
id) as T
inline fun < reified T : View> Activity.find ( id: Int ): T = findViewById(
id) as T
inline fun < reified T : View> Fragment.find ( id: Int ): T = view?
.findViewById ( id) as T inline fun < reified T : View>
RecyclerView.ViewHolder .find ( id: Int ): T = itemView? .findViewById
( id) as T
Usage
}
you can write the following DSL-like code in your production code:
// bigger is defined in the context of `ex` // you can only call this
method inside this context if ( 777 .bigger ()) kotlin.io .println ( "why" )
}
}
Section 28.4: Using extensions with
lambdas
If you have:
}
You can write the following DSL-like code:
If you feel confused with shouldBe above, see the example Infix
approach to build DSL.
Chapter 29: Idioms
Section 29.1: Serializable and
serialVersionUid in Kotlin
To create the serialVersionUID for a class in Kotlin you have a few
options all involving adding a member to the companion object of the
class.
The most concise bytecode comes from a private const val which
will become a private static variable on the containing class, in this
case MySpecialCase:
class MySpecialCase : Serializable {
companion object {
private const val serialVersionUID: Long = 123
}
}
You can also use these forms, each with a side effect of having
getter/setter methods which are not necessary for serialization...
class MySpecialCase : Serializable {
companion object {
private val serialVersionUID: Long = 123 }
}
This creates the static field but also creates a getter as well
getSerialVersionUID on the companion object which is unnecessary.
class MySpecialCase : Serializable {
companion object {
@JvmStatic private val serialVersionUID: Long = 123 }
}
This creates the static field but also creates a static getter as well
getSerialVersionUID on the containing class MySpecialCase which is
unnecessary.
But all work as a method of adding the serialVersionUID to a
Serializable class.
Section 29.2: Delegate to a class
without providing it in the public
constructor
Assume you want to delegate to a class but you do not want to
provide the delegated-to class in the constructor parameter. Instead,
you want to construct it privately, making the constructor caller
unaware of it. At first this might seem impossible because class
delegation allows to delegate only to constructor parameters.
However, there is a way to do it, as given in this answer :
fun makeDir( String path): File { val result = new File ( path)
result.mkdirs ()
return result
}
Section 29.5: Fluent methods in Kotlin
Fluent methods in Kotlin can be the same as Java:
}
But you can also make them more functional by creating an extension
function such as:
}
Which then allows more obviously fluent functions:
fun doSomething() {
return fluently { someOtherAction() }
}
Section 29.6: Filtering a list
val list = listOf( 1 ,2 ,3 ,4 ,5 ,6 )
//filter out even numbers
val even = list.filter { it % 2 == 0 }
println( even) //returns [2,4]
Section 29.7: Creating DTOs
(POJOs/POCOs)
Data classes in kotlin are classes created to do nothing but hold data.
Such classes are marked as data :
data class User( var firstname: String , var lastname: String , var
age: Int )
The code above creates a User class with the following automatically
generated:
Getters and Setters for all properties (getters only for val s)
equals()
hashcode()
toString()
copy()
componentN() (where N is the corresponding property in order of
declaration)
println ( i)
list.add ( "$i" )
}
return list
}
}
this one is your recycler view adapter class and create
main_item.xml file what you want
class RecyclerAdapter : RecyclerView.Adapter <
RecyclerAdapter.ViewHolder >() {
var mItems: ArrayList< String> = ArrayList () lateinit var mClick :
OnClick
card.text = str
card.setOnClickListener { view ->
mClick.onClickListner ( position)
}
}
}
}
Chapter 31: logging in kotlin
Section 31.1: kotlin.logging
class FooWithLogging {
companion object : KLogging()
fun bar() {
logger.info { "hello $name" }
}
try {
doSomething()
}
catch ( e: MyException) {
handle( e)
}
finally {
cleanup()
}
try {
doSomething()
}
catch ( e: FileSystemException) { handle( e)
}
catch ( e: NetworkException) { handle( e)
}
catch ( e: MemoryException) { handle( e)
}
finally {
cleanup()
}
}
Chapter 33: JUnit
Section 33.1: Rules
To add a JUnit rule to a test fixture:
@Rule @JvmField val myRule = TemporaryFolder()
The @JvmField annotation is necessary to expose the backing field
with the same visibility (public) as the myRule property (see answer ).
JUnit rules require the annotated rule field to be public.
Chapter 34: Kotlin Android
Extensions
Kotlin has a built-in view injection for Android, allowing to skip manual
binding or need for frameworks such as ButterKnife. Some of the
advantages are a nicer syntax, better static typing and thus being
less error-prone.
Section 34.1: Using Views
Assuming we have an activity with an example layout called
activity_main.xml :
<Button
android:id = "@+id/my_button"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "My button" />
</LinearLayout>
We can use Kotlin extensions to call the button without any additional
binding like so:
import kotlinx.android.synthetic.main.activity_main.my_button
}
}
You can also import all ids appearing in layout with a * notation
// my_button can be used the same way as before import
kotlinx.android.synthetic.main.activity_main.*
Synthetic views can't be used outside of Activities/Fragments/Views
with that layout inflated:
import kotlinx.android.synthetic.main.activity_main.my_button
class NotAView {
init {
// This sample won't compile! my_button.setText ( "Kotlin rocks!" )
}
}
Section 34.2: Configuration
Start with a properly configured gradle project.
In your project-local (not top-level) build.gradle append extensions
plugin declaration below your Kotlin plugin, on top-level indentation
level.
buildscript { ...
}
}
Under the hood
inline fun View .afterMeasured ( crossinline f: View .() -> Unit ) {
viewTreeObserver.addOnGlobalLayoutListener ( object :
ViewTreeObserver.OnGlobalLayoutListener { override fun
onGlobalLayout() {
}
}
})
}
Section 34.4: Product flavors
Android extensions also work with multiple Android Product Flavors.
For example if we have flavors in build.gradle like so:
android {
productFlavors { paid {
...
}
free {
...
}
}
}
And for example, only the free flavor has a buy button:
<Button
android:id = "@+id/buy_button" android:layout_width =
"wrap_content" android:layout_height = "wrap_content" android:text =
"Buy full version" />
</LinearLayout>
We can bind to the flavor specifically: import
kotlinx.android.synthetic.free.main_activity.buy_button
Chapter 35: Kotlin for Java
Developers
Most people coming to Kotlin do have a programming background in
Java.
This topic collects examples comparing Java to Kotlin, highlighting
the most important differences and those gems Kotlin offers over
Java.
Section 35.1: Declaring Variables
In Kotlin, variable declarations look a bit different than Java's:
val i : Int = 42
They start with either val or var , making the declaration final ("val
ue") or var iable.
The type is noted after the name, separated by a :
Thanks to Kotlin's type inference the explicit type declaration can be
omitted if there is an assignment with a type the compiler is able to
unambiguously detect
Java Kotlin
int i = 42 ; var i = 42 (or var i : Int = 42 )
final int i = 42 ; val i = 42
Section 35.2: Quick Facts
Kotlin does not need ; to end statements
Kotlin is null-safe
Kotlin is 100% Java interoperable
Kotlin has no primitives (but optimizes their object counterparts for
the JVM, if possible) Kotlin classes have properties, not fields
Kotlin offers data classes with auto-generated equals/hashCode
methods and field accessors Kotlin only has runtime Exceptions, no
checked Exceptions
Kotlin has no new keyword . Creating objects is done just by calling
the constructor like any other method. Kotlin supports (limited)
operator overloading . For example, accessing a value of a map
can be written like: val a = someMap[ "key" ]
Kotlin can not only be compiled to byte code for the JVM, but also
into Java Script , enabling you to write both backend and frontend
code in Kotlin
Kotlin is fully compatible with Java 6 , which is especially
interesting in regards for support of (not so) old Android devices
Kotlin is an officially supported language for Android
development
Kotlin's collections have built-in distinction between mutable and
immutable collections . Kotlin supports Coroutines (experimental)
Section 35.3: Equality & Identity
Kotlin uses == for equality (that is, calls equals internally) and === for
referential identity.
Java Kotlin
a.equals ( b); a == b
a == b; a === b
a != b; a !== b
See: https://kotlinlang.org/docs/reference/equality.html
Section 35.4: IF, TRY and others are
expressions, not statements
In Kotlin, if, try and others are expressions (so they do return a value)
rather than (void) statements.
So, for example, Kotlin does not have Java's ternary Elvis Operator ,
but you can write something like this:
val i = if ( someBoolean) 33 else 42
Even more unfamiliar, but equally expressive, is the try expression :
val i = try {
42
}
Chapter 36: Java 8 Stream
Equivalents
Kotlin provides many extension methods on collections and iterables
for applying functional-style operations. A dedicated Sequence type
allows for lazy composition of several such operations.
Section 36.1: Accumulate names in a
List
// Java:
List< String> list = people.stream () .map ( Person:: getName) .collect
( Collectors.toList ());
// Kotlin:
val list = people.map { it.name } // toList() not needed
Section 36.2: Collect example #5 - find
people of legal age, output formatted
string
// Java:
// Kotlin:
val phrase = persons
.filter { it.age >= 18 }
.map { it.name }
.joinToString ( " and " , "In Germany " , " are of legal age." )
println( phrase)
// In Germany Max and Peter and Pamela are of legal age.
And as a side note, in Kotlin we can create simple data classes and
instantiate the test data as follows:
// Kotlin:
// data class has equals, hashcode, toString, and copy methods
automagically data class Person( val name: String , val age: Int )
p -> p.age ,
p -> p.name ,
( name1, name2) -> name1 + ";" + name2));
// Kotlin:
val map1 = persons.map { it.age to it.name } .toMap () println( map1)
// output: {18=Max, 23=Pamela, 12=David}
// Result: duplicates overridden, no exception similar to Java 8
println ( map6)
// output: {18=Max, 23=Peter;Pamela, 12=David} // Result: YAY!!
We just needed to join the matching values to collapse the lists and
provide a transformer to joinToString to move from Person instance to
the Person.name .
Section 36.4: Di erent Kinds of
Streams #7 - lazily iterate Doubles,
map to Int, map to String, print each
// Java:
// a1
// a2
// a3
// Kotlin:
val count = items.filter { it.startsWith ( 't' ) } .size
// but better to not filter, but count with a predicate
val count = items.count { it.startsWith ( 't' ) }
Section 36.6: Convert elements to
strings and concatenate them,
separated by commas
// Java:
// Kotlin:
val joined = things.joinToString () // ", " is used as separator, by
default
Section 36.7: Compute sum of salaries
of employee
// Java:
int total = employees.stream ()
.collect ( Collectors.summingInt ( Employee:: getSalary)));
// Kotlin:
val total = employees.sumBy { it.salary }
Section 36.8: Group employees by
department
// Java:
Map< Department, List< Employee>> byDept
= employees.stream ()
.collect ( Collectors.groupingBy ( Employee:: getDepartment));
// Kotlin:
val byDept = employees.groupBy { it.department }
Section 36.9: Compute sum of salaries
by department
// Java:
Map< Department, Integer> totalByDept
= employees.stream ()
.collect ( Collectors.groupingBy ( Employee:: getDepartment,
Collectors.summingInt ( Employee:: getSalary)));
// Kotlin:
val totalByDept = employees.groupBy { it.dept } .mapValues { it.value
.sumBy { it.salary }}
Section 36.10: Partition students into
passing and failing
// Java:
Map< Boolean , List< Student>> passingFailing =
students.stream ()
.collect ( Collectors.partitioningBy ( s -> s.getGrade () >=
PASS_THRESHOLD));
// Kotlin:
val passingFailing = students.partition { it.grade >=
PASS_THRESHOLD }
Section 36.11: Names of male
members
// Java:
// Kotlin:
val namesOfMaleMembers = roster.filter { it.gender == Person.Sex
.MALE } .map { it.name }
Section 36.12: Group names of
members in roster by gender
// Java:
Map< Person.Sex , List< String>> namesByGender =
roster.stream () .collect (
Collectors. groupingBy (
Person:: getGender,
Collectors.mapping (
Person:: getName,
Collectors.toList ())));
// Kotlin:
val namesByGender = roster.groupBy { it.gender } .mapValues {
it.value .map { it.name } }
Section 36.13: Filter a list to another
list
// Java:
// Kotlin:
val filtered = items.filter { item.startsWith ( 'o' ) }
Section 36.14: Finding shortest string
a list
// Java:
// Kotlin:
val shortest = items.minBy { it.length }
Section 36.15: Di erent Kinds of
Streams #2 - lazily using first item if
exists
// Java:
Stream.of ( "a1" , "a2" , "a3" ) .findFirst ()
.ifPresent ( System .out :: println);
// Kotlin:
sequenceOf( "a1" , "a2" , "a3" ) .firstOrNull ()? .apply (:: println)
Section 36.16: Di erent Kinds of
Streams #3 - iterate a range of Integers
// Java:
IntStream.range ( 1 , 4 ) .forEach ( System .out :: println);
// Kotlin: (inclusive range)
( 1 ..3 ) .forEach (:: println)
Section 36.17: Di erent Kinds of
Streams #4 - iterate an array, map the
values, calculate the average
// Java:
// Kotlin:
arrayOf( 1 ,2 ,3 ) .map { 2 * it + 1 } .average () .apply (:: println)
Section 36.18: Di erent Kinds of
Streams #5 - lazily iterate a list of
strings, map the values, convert to Int,
find max
// Java:
// Kotlin:
sequenceOf( "a1" , "a2" , "a3" )
.map { it.substring ( 1 ) }
.map ( String :: toInt)
.max () .apply (:: println)
Section 36.19: Di erent Kinds of
Streams #6 - lazily iterate a stream of
Ints, map the values, print results
// Java:
IntStream. range ( 1 , 4 )
.mapToObj ( i -> "a" + i)
.forEach ( System .out :: println);
// a1
// a2
// a3
myList. stream ()
.filter ( s -> s.startsWith ( "c" )) .map ( String :: toUpperCase)
.sorted ()
.forEach ( System .out :: println);
// C1
// C2
// Kotlin:
val list = listOf( "a1" , "a2" , "b1" , "c2" , "c1" )
list.filter { it.startsWith ( 'c' ) } .map ( String :: toUpperCase) .sorted ()
// Kotlin:
listOf( "a1" , "a2" , "a3" ) .firstOrNull ()? .apply (:: println)
or, create an extension function on String called ifPresent:
// Kotlin:
inline fun String ? .ifPresent ( thenDo: ( String )-> Unit ) = this ?
.apply { thenDo( this ) }
// now use the new extension function:
listOf( "a1" , "a2" , "a3" ) .firstOrNull () .ifPresent (:: println)
See also: apply () function
See also: Extension Functions
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
Then you need to apply this plugin to your project. The way you do
this differs when targeting different platforms:
Targeting JVM
apply plugin: 'kotlin'
Targeting Android
apply plugin: 'kotlin-android'
Targeting JS
apply plugin: 'kotlin2js'
These are the default paths:
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
If you want to use Kotlin Reflection you'll also need to add compile
"org.jetbrains.kotlin:kotlinreflect:$kotlin_version"
Section A.2: Using Android Studio
Android Studio can configure Kotlin automatically in an Android
project.
Install the plugin
To install the Kotlin plugin, go to File > Settings > Editor > Plugins >
Install JetBrains Plugin... > Kotlin > Install, then restart Android Studio
when prompted.
Configure a project
Create an Android Studio project as normal, then press Ctrl + Shift +
A . In the search box, type "Configure Kotlin in Project" and press
Enter.
update the content of the build.gradle .kts based on your needs, you
can use as inspiration the scripts in the project just cloned or in one of
its samples
now open Intellij and open your project, in the explorer window, it
should be recognized as a Gradle project, if not, expand it first.
after opening, let Intellij works, open build.gradle .kts and check if
there are any error. If the highlighting is not working and/or is
everything marked red, then close and reopen Intellij
open the Gradle window and refresh it
If you are on Windows, you may encounter this bug , download the
full Gradle 3.3 distribution and use that instead the one provided.
Related .
OSX and Ubuntu work out of the box.
Small bonus, if you want to avoid all the hassle of publishing on
Maven and similar, use Jitpack , the lines to add are almost identical
compared to Groovy. You can take inspiration from this project of
mine.
Credits
Thank you greatly to all the people from Stack Overflow
Documentation who helped provide this content, more changes can
be sent to web@petercv.com for new content to be published or
updated
Aaron Christiansen
Abdullah
Adam Arold
Alex Facciorusso
Ascension
atok
Avijit Karmakar
baha
Brad
byxor
Caelum
cyberscientist
Dávid Tímár
David Soroko
Divya
egor.zhdan
elect
Espen
Gerson
glee8e
Héctor
hotkey
ice1000
Jan Vladimir Mostert
Januson
Jayson Minard
Jemo Mgebrishvili
jenglert
jereksel
KeksArmee
Kevin Robatel
Kirill Rakhman
Konrad Jamrozik
madhead
mayojava
memoizr
Mohit Suthar
Mood
Nihal Saxena
olivierlemasle
oshai
Parker Hoyes
razzledazzle
Rich Kuzsma
Ritave
Robin
Ruckus T
Chapters 7, 29 and 38
Chapter 9
Chapter 29
Chapter 9
Chapter 5
Chapter 26
Chapter 17
Chapter 7
Chapter 36
Chapters 8 and 16
Chapter 22
Chapter 1
Chapter 27
Chapter 6
Chapters 19 and 20
Chapter 4
Chapter 38
Chapter 12
Chapter 36
Chapters 7 and 20
Chapters 22 and 29
Chapter 18
Chapter 28
Chapter 19
Chapter 3
Chapters 1, 7, 18, 19, 27, 29 and 36
Chapters 21 and 34
Chapter 33
Chapter 32
Chapters 7, 14, 16 and 18
Chapter 23
Chapters 6, 9 and 26
Chapters 27, 29 and 31
Chapters 7, 26 and 38
Chapters 10 and 29
Chapter 13
Chapter 30
Chapter 22
Chapter 11
Chapter 31
Chapter 31
Chapters 1 and 27
Chapters 10, 14, 27 and 29
Chapter 13
Chapters 19, 26 and 34
Chapters 9, 10, 14 and 19
Chapter 1
Sach
Sam
Sean Reilly
Seaskyways
SerCe
Shinoo Goyal
Slav
Spidfire
technerd
Thorsten Schleinzer Travis
UnKnown
Chapter 1
Chapters 3, 4, 15 and 25 Chapter 1
Chapter 25
Chapters 6 and 14
Chapter 2
Chapters 16 and 24 Chapters 7, 9, 14 and 37 Chapter 14
Chapters 14 and 35 Chapter 12
Chapters 1 and 4