<commit_before><!-- .slide: class="borderless big-th" style="text-align: left;" -->

### Kotlin: A language for productive developers <!-- .element: style="text-align: center;" -->

<br/>

<NAME> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | <NAME>
:------------------------------------------------------------- | ----------------------------:
*App&Web*                                                      | *Quadbits*
[@voghDev](https://twitter.com/voghDev)                        | [@jrgonzalezg](https://twitter.com/jrgonzalezg)

---

## Introduction

- The Kotlin language
  - Basic features
  - Functional Programming (FP)
  - Extension functions
  - Kotlin on Android
- Advanced topics
  - Advanced Types
  - Domain Specific Languages (DSLs)
  - Coroutines
- To know more

Note: Consider talking about anko and other concrete details on Android Dev

---

## The Kotlin programming language

- Expressive
- Type-safe
<!-- .element: class="fragment" -->
- Functional (we’ll focus on that later)
<!-- .element: class="fragment" -->
- Created by JetBrains
<!-- .element: class="fragment" -->
- Official ! First class support in Android since Google I/O 2017
<!-- .element: class="fragment" -->
- Official support in Spring Framework 5.0 too (final version ~ July 2017))
<!-- .element: class="fragment" -->
- Made by and for Java “sufferers”
<!-- .element: class="fragment" -->

---

## Multiple targets

- Goal: Make it possible to use Kotlin for all parts of any project
- **Kotlin/JVM**
<!-- .element: class="fragment" data-fragment-index="1" -->
  - All features and the whole standard library, production-ready
<!-- .element: class="fragment" data-fragment-index="1" -->
  - 100% Interoperable with Java and Android
<!-- .element: class="fragment" data-fragment-index="1" -->
- **JavaScript**
<!-- .element: class="fragment" data-fragment-index="2" -->
  - All language features since Kotlin 1.1 and a large part of the standard library
<!-- .element: class="fragment" data-fragment-index="2" -->
  - JavaScript interoperability (including Node.js and browser support)
<!-- .element: class="fragment" data-fragment-index="2" -->
- **Kotlin / Native**
<!-- .element: class="fragment" data-fragment-index="3" -->
  - Machine code through LLVM
<!-- .element: class="fragment" data-fragment-index="3" -->
  - Mac OS X 10.10 and later (x86-64), x86-64 Ubuntu Linux (14.04, 16.04 and later), Apple iOS (arm64), Raspberry Pi, cross-compiled on Linux host, more to come...
<!-- .element: class="fragment" data-fragment-index="3" -->
  - Not yet feature complete
<!-- .element: class="fragment" data-fragment-index="3" -->

---

## Basic Features

- Data classes
- Null-safety
- Inheritance (open, closed classes)
- Interfaces with attrs, default methods
- Default values for attributes
- Smart casts
- Elvis operator
- Multiple inheritance
- Testability (JUnit4 100% supported)
- with, apply, let functions. Introduction to FP

---

<!-- .slide: style="text-align: left;" -->

## Data classes

- Java

```java
public class Book {
  int id;
  String title;
  int coverId;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public int getCoverId() {
    return coverId;
  }

  public void setCoverId(int coverId) {
    this.coverId = coverId;
  }
}
```
<!-- .element: style="font-size: 30%" -->

- Kotlin
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
data class Book(val id: Int, val title: String, val coverId: Int)
```
<!-- .element: class="fragment" data-fragment-index="1" -->

---

## Null-Safety

Java (all non-primitive types are nullable in an unsafe way)

```java
Book book = null;
book.getTitle();
```

This code causes NPE!

---

## Null-Safety

Kotlin - Trying to use null in Non-Null types

```kotlin
val book: Book = null
print(book.title)
```

This code does not compile - "null can not be a value of a non-null type Book"

![null1](img/null1.png)

---

## Null-Safety - Nullable types

```kotlin
val book: Book? = null
print(book.title)
```

This code does not compile - "only safe (?.) or non-null asserted (!!) calls are allowed on a nullable receiver of type Book"

![null2](img/null2.png)

One way to make this work would be using the ? operator

---

## Null-Safety - Nullable types

```kotlin
val book: Book? = null
print(book?.title)
```

This code works, prints nothing. "title" is never evaluated because "book" is null. NPE is avoided

---

## Null-Safety - Nullable types

You can also assert non-null using the \!\! operator

```kotlin
val book: Book? = null
print(book!!.title)
```

This causes NPE, as we are forcing "book.title" to be evaluated, but "book" is null. Would behave similar to Java

---

## Inheritance

Given the previous data class "Book"

```kotlin
data class Book(val id: Int, val title: String, val coverId: Int)
```

We want to create a subclass called "Novel"
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
class Novel(id: Int = 0, title: String = "", coverId: Int = 0,
        var summary: String = "") : Book(id, title, coverId)
```
<!-- .element: class="fragment" data-fragment-index="2" -->

We find that we can't. Compiler yields "this type is final, so we can't inherit from it"
<!-- .element: class="fragment" data-fragment-index="3" -->

![inheritance1](img/inheritance1.png)
<!-- .element: class="fragment" data-fragment-index="3" -->

Book needs to be declared as open class for inheritance to work
<!-- .element: class="fragment" data-fragment-index="4" -->

```kotlin
open class Book(val id: Int, val title: String, val coverId: Int)
```
<!-- .element: class="fragment" data-fragment-index="4" -->

---

## Interfaces with attributes and default methods

In Kotlin, interfaces can have attributes

Java
<!-- .element: class="fragment" data-fragment-index="1" -->

```java
public interface Request<T> {
  T client; // Does not compile

  void execute();
}
```
<!-- .element: class="fragment" data-fragment-index="1" -->

Kotlin
<!-- .element: class="fragment" data-fragment-index="2" -->

```kotlin
interface Request<T> {
  val client : T

  fun execute()
}
```
<!-- .element: class="fragment" data-fragment-index="2" -->

---

## Interfaces with attributes and default methods

Java: Default template methods are supported in abstract classes

```java
public abstract class Request<T> {
  T client; // Compiles

  void execute() {
    // Default implementation for method
  }
}
```
<!-- .element: class="fragment" data-fragment-index="1" -->

Kotlin
<!-- .element: class="fragment" data-fragment-index="2" -->

```kotlin
interface Request<T> {
  val client : T

  fun execute() {
    // Default implementation
  }
}
```
<!-- .element: class="fragment" data-fragment-index="2" -->

---

## Default values for attributes

Java: Telescoping constructor problem - Builder pattern

Kotlin: Attributes with default values to the rescue!
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
data class Book(val id: Int = 0, val title: String = "", val coverId: Int = 0)

fun initBooks() {
  val books = listOf(
    Book(id = 1),
    Book(id = 2, title = "<NAME>"),
    Book(id = 3, title = "<NAME>", coverId = 254),
    Book()
  )

  books.forEach {
    print(it.title)
  }
}
```
<!-- .element: class="fragment" data-fragment-index="1" -->

---

## Smart casts

Null safety

```kotlin
val book : Book?

book.title // Does not compile

book?.title // Ok

if (book != null) {
  book.title // Ok
}
```

Smart type casts
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
open class Book(val id: Int = 0, val title: String = "", val coverId: Int = 0)

class Novel(id: Int = 0, title: String = "", coverId: Int = 0,
        var summary: String = "") : Book(id, title, coverId)
```
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
val novel: Book = Novel()

(novel as Novel).summary = "Once upon a time..."

if (novel is Novel) {
  novel.summary = "Once upon a time..."
}
```
<!-- .element: class="fragment" data-fragment-index="2" -->

---

## Elvis operator

Java

```Java
String title;

System.out.println(title != null ? title : "-");
```

```Java
List<Novel> novels;

System.out.println(
    novels != null && novels.size() > 0 ?
        String.format("%d novels", novels.size()) :
        "No novels"
);
```
<!-- .element: class="fragment" data-fragment-index="2" -->

Kotlin
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
val title: String?

print(title ?: "-")
```
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
val novels : List<Novel>?

print("${novels?.size ?: "No"} novels")
```
<!-- .element: class="fragment" data-fragment-index="4" -->

---

## Multiple inheritance

```kotlin
interface Transportation {
    fun move()
    fun emitCO2()
}
```

```kotlin
interface PieceOfMuseum {
    fun shine()
    fun lookGreat()
}

```

A car can be a mean of Transportation, and also a Piece of museum
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
class Car : Transportation, PieceOfMuseum {
    override fun move() {
    }

    override fun shine() {
    }

    override fun emitCO2() {
    }

    override fun lookGreat() {
    }
}
```
<!-- .element: class="fragment" data-fragment-index="2" -->

---

## Multiple inheritance by delegation

Car class is built with two parameters, one is responsible for the "Transportation" behavior, and the other one for the "PieceOfMuseum"

```kotlin
class LuxuryRacingCar(t: Transportation, p: PieceOfMuseum) :
        Transportation by t, PieceOfMuseum by p {
    fun letTheShowBegin() {
        move()
        shine()
        emitCO2()
        lookGreat()
    }
}
```

---

## Testability

- JUnit is 100% supported
- Test names are very readable, near specification of real requirements

```kotlin
@Test
fun 'should request a List of users on start'() {
    val presenter = UserListPresenter(mockContext, userRepository)

    presenter.view = mockView
    presenter.initialize()

    verify(userRepository, times(1))?.getUsers()
}
```

---

## Testability: Mockito support

- Similarly to Java, Mockito is supported
- A Small issue related to final classes (easy to solve)
- [mockito-kotlin](https://github.com/nhaarman/mockito-kotlin) adds some syntactic sugar

```kotlin
@Test
fun 'should show a list of users if previous request has results'() {
    val presenter = UserListPresenter(mockContext, userRepository)

    `when`(userRepository.getUsers()).thenReturn(listOf(User(name = "John")))

    presenter.view = mockView
    presenter.initialize()

    verify(mockView, times(1))?.showUsers(anyList())
}
```

---

## Testability: Mockito support

- Typical Mockito annotations and **setUp** method - similar to Java

```kotlin
@Mock lateinit var userRepository: UserRepository

@Mock lateinit var mockContext: Context

@Mock lateinit var mockView: SomeDetailPresenter.MVPView

@Before
fun setUp() {
    MockitoAnnotations.initMocks(this)
}
```

Test names can be made even more readable using third-party components like
<!-- .element: class="fragment" data-fragment-index="2" -->
[kotlintest](https://github.com/kotlintest/kotlintest)

---

## Functional Programming (FP)

%%%

### Some Principles

- A computation can be viewed as a **function** that maps inputs to outputs

- **Pure functions**
  - <div>Always return the **same result** for the **same arguments**</div>
<!-- .element: class="fragment" data-fragment-index="1" -->
  - <div>The evaluation of the result has **no observable side effects**</div>
<!-- .element: class="fragment" data-fragment-index="2" -->
  - <div>A functions that takes no parameters must return a constant value</div>
<!-- .element: class="fragment" data-fragment-index="3" -->
  - <div>Function **signature does not lie**</div>
<!-- .element: class="fragment" data-fragment-index="4" -->
    - You can infer what the function may do by its signature
<!-- .element: class="fragment" data-fragment-index="4" -->
    - If the function has no parameters it should return a constant
<!-- .element: class="fragment" data-fragment-index="4" -->

%%%

<!-- .slide: style="text-align: left;" -->

### Some Principles <!-- .element: style="text-align: center;" -->

- **Immutability** by default
  - <div>Immutable data **can not be changed** after it is created</div>
<!-- .element: class="fragment" data-fragment-index="1" -->
  - <div>**State changes** are represented by new instances of data</div>
<!-- .element: class="fragment" data-fragment-index="2" -->
  - <div>**Original instances** are not affected</div>
<!-- .element: class="fragment" data-fragment-index="3" -->
  - <div>Simplifies multi-threaded applications (**race conditions**)</div>
<!-- .element: class="fragment" data-fragment-index="4" -->

```kotlin
data class Book(val id: Int, val title: String, val coverId: Int)

val book = Book(id = 3, title = "<NAME>", coverId = 254) // Immutable
val modifiedBook = book.copy(coverId = 2) // Copy is a separate immutable instance
```
<!-- .element: class="fragment" data-fragment-index="5" -->

- <div>The value of `book` can not be changed</div>
<!-- .element: class="fragment" data-fragment-index="6" -->
- <div>Creation of `modifiedBook` does not affect the value of book</div>
<!-- .element: class="fragment" data-fragment-index="7" -->
- <div>`modifiedBook` is also immutable</div>
<!-- .element: class="fragment" data-fragment-index="8" -->

%%%

### First-class Functions

- Functions as a **first-class citizen** of the language

- <div>**Higher-order functions**</div> <!-- .element: class="fragment" data-fragment-index="1" -->
  - <div>Functions can **return functions**</div>
<!-- .element: class="fragment" data-fragment-index="2" -->
  - <div>Functions can be **passed as arguments** to other functions</div>
<!-- .element: class="fragment" data-fragment-index="3" -->
  - <div>Functions can be **assigned to variables** and stored inside other data structures</div>
<!-- .element: class="fragment" data-fragment-index="4" -->

- <div>Lambda Expressions</div> <!-- .element: class="fragment" data-fragment-index="5" -->
  - <div>Functions that are **not declared** but **passed immediately** as **an expression**</div>
<!-- .element: class="fragment" data-fragment-index="5" -->

%%%

### Lambda Expressions

- Always **surrounded by curly braces**
- map on List is a higher-order function
- You can pass a lambda expression as the transform function

```kotlin
fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
    val result = arrayListOf<R>()
    for (item in this)
        result.add(transform(item))
    return result
}

val ints = listOf(1, 2, 3)

val doubled = ints.map { value -> value * 2 } // [2, 4, 6]

println(ints.map { it * 3 } ) // [3, 6, 9] - Implicit name for single parameter
```

%%%

<!-- .slide: style="text-align: left;" -->

### Collections <!-- .element: style="text-align: center;" -->

- Kotlin distinguishes **mutable** and **immutable** collections
  - <div>You have control over when collections can be edited</div>
<!-- .element: class="fragment" data-fragment-index="1" -->
  - <div>Helps to eliminate bugs and to design better APIs</div>
<!-- .element: class="fragment" data-fragment-index="2" -->

```kotlin
val ids: List<Int> = listOf(1, 2, 3)
println(ids.get(2)) // 3
ids.add(0, 6) // Unresolved reference: add

val numbers: MutableList<Int> = mutableListOf(5, 9, 3)
numbers.add(0, 6)
println(numbers) // [6, 5, 9, 3]
```
<!-- .element: class="fragment" data-fragment-index="2" -->

- <div>Currently the *immutable* collections are really **read-only versions of mutable collections**</div>
<!-- .element: class="fragment" data-fragment-index="3" -->
- <div>[Immutable Collections Library for Kotlin](https://github.com/Kotlin/kotlinx.collections.immutable)</div>
<!-- .element: class="fragment" data-fragment-index="4" -->
  - <div>Prototypes of real immutable collections with the performance characteristics of typical **FP persistent data structures**</div>
<!-- .element: class="fragment" data-fragment-index="4" -->

%%%

### Functional Combinators

- <NAME>: *A combinator is a function which builds programs fragments from program fragments*
<!-- .element: class="fragment" data-fragment-index="1" -->

- Functional Programming languages usually provide a big set of **combinators for collections**
<!-- .element: class="fragment" data-fragment-index="2" -->

```kotlin
val strings = listOf("Kotlin", "is", "here", "to", "stay")

val result = strings.filter { it.length == 4 }
        .map(String::toUpperCase) // Method reference
        .sortedByDescending { it } // Natural sort order
        .joinToString(separator = " ")

println(result) // STAY HERE
```
<!-- .element: class="fragment" data-fragment-index="3" -->

%%%

### Functional Combinators

```kotlin
val strings = listOf("Kotlin", "is", "here", "to", "stay")

val result: Map<Char, Int> = strings
        .filterNot { it.contains('t') } // Keep only strings without 't'
        .flatMap { it.toList() } // A list of chars from the list of strings
        .groupBy { it } // A map from each char to its occurrences
        .mapValues { it.value.size } // A map from char to occurrence count
        .toList() // List of pairs (char, count)
        .sortedBy { it.second } // Sorted by increasing count

println(result)
// [(i, 1), (s, 1), (h, 1), (r, 1), (e, 2)]

```

---

## with, let, apply

Java

```java
final TextView textView = new TextView(this);
textView.setText("Hello!");
textView.setTextSize(16f);
textView.setTextColor(ContextCompat.getColor(this, android.R.color.white));
```

Kotlin

```kotlin
val textView : TextView = TextView(this)
with(textView) {
    text = ""
    textSize = 16f
    setTextColor(color(android.R.color.white))
}
```

Optional receiver can't be used in this case

---

## with, let, apply

Java

```java
LinearLayout linearLayout = new LinearLayout(this);
if (textView != null) {
    linearLayout.addView(textView);
    setContentView(linearLayout);
}
```

Kotlin

```kotlin
val linearLayout = LinearLayout(this)
textView?.let {
    linearLayout.addView(it)
    setContentView(linearLayout)
}
```

let won't be applied if textView is null

---

## with, let, apply

Java

```java
TextView textView = new TextView(this);
textView.setText("Hello!");
textView.setTextSize(16f);
textView.setTextColor(ContextCompat.getColor(this, android.R.color.white));
```

Kotlin

```kotlin
val textView: TextView = TextView(this).apply {
    text = "Hello!"
    textSize = 16f
    setTextColor(color(android.R.color.white))
}
```

textView can also be optional and this code will still work

---

## Extension functions


- Ability to extend a class with new functionality without inheriting from it
- No need to use patterns like **Decorator**
- Extension functions do not modify the receiver classes
- Excellent substitute to **Helper** methods and **Util** classes

---

## Extension functions

- Declared with class name as prefix, then function name

```kotlin
fun Activity.screenWidth(): Int {
    val metrics: DisplayMetrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.widthPixels
}

fun Activity.screenHeight(): Int {
    val metrics: DisplayMetrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.heightPixels
}
```

---

## Extension functions

Then inside my Activity class

```kolin
fun loadImage(url: String) {
    Picasso.with(this)
        .load(url)
        .resize(screenWidth(), 200)
        .into(imageView)
}
```<commit_msg>Added a couple of slides about anko<commit_after><!-- .slide: class="borderless big-th" style="text-align: left;" -->

### Kotlin: A language for productive developers <!-- .element: style="text-align: center;" -->

<br/>

<NAME> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | <NAME>
:------------------------------------------------------------- | ----------------------------:
*App&Web*                                                      | *Quadbits*
[@voghDev](https://twitter.com/voghDev)                        | [@jrgonzalezg](https://twitter.com/jrgonzalezg)

---

## Introduction

- The Kotlin language
  - Basic features
  - Functional Programming (FP)
  - Extension functions
  - Kotlin on Android
- Advanced topics
  - Advanced Types
  - Domain Specific Languages (DSLs)
  - Coroutines
- To know more

Note: Consider talking about anko and other concrete details on Android Dev

---

## The Kotlin programming language

- Expressive
- Type-safe
<!-- .element: class="fragment" -->
- Functional (we’ll focus on that later)
<!-- .element: class="fragment" -->
- Created by JetBrains
<!-- .element: class="fragment" -->
- Official ! First class support in Android since Google I/O 2017
<!-- .element: class="fragment" -->
- Official support in Spring Framework 5.0 too (final version ~ July 2017))
<!-- .element: class="fragment" -->
- Made by and for Java “sufferers”
<!-- .element: class="fragment" -->

---

## Multiple targets

- Goal: Make it possible to use Kotlin for all parts of any project
- **Kotlin/JVM**
<!-- .element: class="fragment" data-fragment-index="1" -->
  - All features and the whole standard library, production-ready
<!-- .element: class="fragment" data-fragment-index="1" -->
  - 100% Interoperable with Java and Android
<!-- .element: class="fragment" data-fragment-index="1" -->
- **JavaScript**
<!-- .element: class="fragment" data-fragment-index="2" -->
  - All language features since Kotlin 1.1 and a large part of the standard library
<!-- .element: class="fragment" data-fragment-index="2" -->
  - JavaScript interoperability (including Node.js and browser support)
<!-- .element: class="fragment" data-fragment-index="2" -->
- **Kotlin / Native**
<!-- .element: class="fragment" data-fragment-index="3" -->
  - Machine code through LLVM
<!-- .element: class="fragment" data-fragment-index="3" -->
  - Mac OS X 10.10 and later (x86-64), x86-64 Ubuntu Linux (14.04, 16.04 and later), Apple iOS (arm64), Raspberry Pi, cross-compiled on Linux host, more to come...
<!-- .element: class="fragment" data-fragment-index="3" -->
  - Not yet feature complete
<!-- .element: class="fragment" data-fragment-index="3" -->

---

## Basic Features

- Data classes
- Null-safety
- Inheritance (open, closed classes)
- Interfaces with attrs, default methods
- Default values for attributes
- Smart casts
- Elvis operator
- Multiple inheritance
- Testability (JUnit4 100% supported)
- with, apply, let functions. Introduction to FP

---

<!-- .slide: style="text-align: left;" -->

## Data classes

- Java

```java
public class Book {
  int id;
  String title;
  int coverId;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public int getCoverId() {
    return coverId;
  }

  public void setCoverId(int coverId) {
    this.coverId = coverId;
  }
}
```
<!-- .element: style="font-size: 30%" -->

- Kotlin
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
data class Book(val id: Int, val title: String, val coverId: Int)
```
<!-- .element: class="fragment" data-fragment-index="1" -->

---

## Null-Safety

Java (all non-primitive types are nullable in an unsafe way)

```java
Book book = null;
book.getTitle();
```

This code causes NPE!

---

## Null-Safety

Kotlin - Trying to use null in Non-Null types

```kotlin
val book: Book = null
print(book.title)
```

This code does not compile - "null can not be a value of a non-null type Book"

![null1](img/null1.png)

---

## Null-Safety - Nullable types

```kotlin
val book: Book? = null
print(book.title)
```

This code does not compile - "only safe (?.) or non-null asserted (!!) calls are allowed on a nullable receiver of type Book"

![null2](img/null2.png)

One way to make this work would be using the ? operator

---

## Null-Safety - Nullable types

```kotlin
val book: Book? = null
print(book?.title)
```

This code works, prints nothing. "title" is never evaluated because "book" is null. NPE is avoided

---

## Null-Safety - Nullable types

You can also assert non-null using the \!\! operator

```kotlin
val book: Book? = null
print(book!!.title)
```

This causes NPE, as we are forcing "book.title" to be evaluated, but "book" is null. Would behave similar to Java

---

## Inheritance

Given the previous data class "Book"

```kotlin
data class Book(val id: Int, val title: String, val coverId: Int)
```

We want to create a subclass called "Novel"
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
class Novel(id: Int = 0, title: String = "", coverId: Int = 0,
        var summary: String = "") : Book(id, title, coverId)
```
<!-- .element: class="fragment" data-fragment-index="2" -->

We find that we can't. Compiler yields "this type is final, so we can't inherit from it"
<!-- .element: class="fragment" data-fragment-index="3" -->

![inheritance1](img/inheritance1.png)
<!-- .element: class="fragment" data-fragment-index="3" -->

Book needs to be declared as open class for inheritance to work
<!-- .element: class="fragment" data-fragment-index="4" -->

```kotlin
open class Book(val id: Int, val title: String, val coverId: Int)
```
<!-- .element: class="fragment" data-fragment-index="4" -->

---

## Interfaces with attributes and default methods

In Kotlin, interfaces can have attributes

Java
<!-- .element: class="fragment" data-fragment-index="1" -->

```java
public interface Request<T> {
  T client; // Does not compile

  void execute();
}
```
<!-- .element: class="fragment" data-fragment-index="1" -->

Kotlin
<!-- .element: class="fragment" data-fragment-index="2" -->

```kotlin
interface Request<T> {
  val client : T

  fun execute()
}
```
<!-- .element: class="fragment" data-fragment-index="2" -->

---

## Interfaces with attributes and default methods

Java: Default template methods are supported in abstract classes

```java
public abstract class Request<T> {
  T client; // Compiles

  void execute() {
    // Default implementation for method
  }
}
```
<!-- .element: class="fragment" data-fragment-index="1" -->

Kotlin
<!-- .element: class="fragment" data-fragment-index="2" -->

```kotlin
interface Request<T> {
  val client : T

  fun execute() {
    // Default implementation
  }
}
```
<!-- .element: class="fragment" data-fragment-index="2" -->

---

## Default values for attributes

Java: Telescoping constructor problem - Builder pattern

Kotlin: Attributes with default values to the rescue!
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
data class Book(val id: Int = 0, val title: String = "", val coverId: Int = 0)

fun initBooks() {
  val books = listOf(
    Book(id = 1),
    Book(id = 2, title = "<NAME>"),
    Book(id = 3, title = "<NAME>", coverId = 254),
    Book()
  )

  books.forEach {
    print(it.title)
  }
}
```
<!-- .element: class="fragment" data-fragment-index="1" -->

---

## Smart casts

Null safety

```kotlin
val book : Book?

book.title // Does not compile

book?.title // Ok

if (book != null) {
  book.title // Ok
}
```

Smart type casts
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
open class Book(val id: Int = 0, val title: String = "", val coverId: Int = 0)

class Novel(id: Int = 0, title: String = "", coverId: Int = 0,
        var summary: String = "") : Book(id, title, coverId)
```
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
val novel: Book = Novel()

(novel as Novel).summary = "Once upon a time..."

if (novel is Novel) {
  novel.summary = "Once upon a time..."
}
```
<!-- .element: class="fragment" data-fragment-index="2" -->

---

## Elvis operator

Java

```Java
String title;

System.out.println(title != null ? title : "-");
```

```Java
List<Novel> novels;

System.out.println(
    novels != null && novels.size() > 0 ?
        String.format("%d novels", novels.size()) :
        "No novels"
);
```
<!-- .element: class="fragment" data-fragment-index="2" -->

Kotlin
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
val title: String?

print(title ?: "-")
```
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
val novels : List<Novel>?

print("${novels?.size ?: "No"} novels")
```
<!-- .element: class="fragment" data-fragment-index="4" -->

---

## Multiple inheritance

```kotlin
interface Transportation {
    fun move()
    fun emitCO2()
}
```

```kotlin
interface PieceOfMuseum {
    fun shine()
    fun lookGreat()
}

```

A car can be a mean of Transportation, and also a Piece of museum
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
class Car : Transportation, PieceOfMuseum {
    override fun move() {
    }

    override fun shine() {
    }

    override fun emitCO2() {
    }

    override fun lookGreat() {
    }
}
```
<!-- .element: class="fragment" data-fragment-index="2" -->

---

## Multiple inheritance by delegation

Car class is built with two parameters, one is responsible for the "Transportation" behavior, and the other one for the "PieceOfMuseum"

```kotlin
class LuxuryRacingCar(t: Transportation, p: PieceOfMuseum) :
        Transportation by t, PieceOfMuseum by p {
    fun letTheShowBegin() {
        move()
        shine()
        emitCO2()
        lookGreat()
    }
}
```

---

## Testability

- JUnit is 100% supported
- Test names are very readable, near specification of real requirements

```kotlin
@Test
fun 'should request a List of users on start'() {
    val presenter = UserListPresenter(mockContext, userRepository)

    presenter.view = mockView
    presenter.initialize()

    verify(userRepository, times(1))?.getUsers()
}
```

---

## Testability: Mockito support

- Similarly to Java, Mockito is supported
- A Small issue related to final classes (easy to solve)
- [mockito-kotlin](https://github.com/nhaarman/mockito-kotlin) adds some syntactic sugar

```kotlin
@Test
fun 'should show a list of users if previous request has results'() {
    val presenter = UserListPresenter(mockContext, userRepository)

    `when`(userRepository.getUsers()).thenReturn(listOf(User(name = "John")))

    presenter.view = mockView
    presenter.initialize()

    verify(mockView, times(1))?.showUsers(anyList())
}
```

---

## Testability: Mockito support

- Typical Mockito annotations and **setUp** method - similar to Java

```kotlin
@Mock lateinit var userRepository: UserRepository

@Mock lateinit var mockContext: Context

@Mock lateinit var mockView: SomeDetailPresenter.MVPView

@Before
fun setUp() {
    MockitoAnnotations.initMocks(this)
}
```

Test names can be made even more readable using third-party components like
<!-- .element: class="fragment" data-fragment-index="2" -->
[kotlintest](https://github.com/kotlintest/kotlintest)

---

## Functional Programming (FP)

%%%

### Some Principles

- A computation can be viewed as a **function** that maps inputs to outputs

- **Pure functions**
  - <div>Always return the **same result** for the **same arguments**</div>
<!-- .element: class="fragment" data-fragment-index="1" -->
  - <div>The evaluation of the result has **no observable side effects**</div>
<!-- .element: class="fragment" data-fragment-index="2" -->
  - <div>A functions that takes no parameters must return a constant value</div>
<!-- .element: class="fragment" data-fragment-index="3" -->
  - <div>Function **signature does not lie**</div>
<!-- .element: class="fragment" data-fragment-index="4" -->
    - You can infer what the function may do by its signature
<!-- .element: class="fragment" data-fragment-index="4" -->
    - If the function has no parameters it should return a constant
<!-- .element: class="fragment" data-fragment-index="4" -->

%%%

<!-- .slide: style="text-align: left;" -->

### Some Principles <!-- .element: style="text-align: center;" -->

- **Immutability** by default
  - <div>Immutable data **can not be changed** after it is created</div>
<!-- .element: class="fragment" data-fragment-index="1" -->
  - <div>**State changes** are represented by new instances of data</div>
<!-- .element: class="fragment" data-fragment-index="2" -->
  - <div>**Original instances** are not affected</div>
<!-- .element: class="fragment" data-fragment-index="3" -->
  - <div>Simplifies multi-threaded applications (**race conditions**)</div>
<!-- .element: class="fragment" data-fragment-index="4" -->

```kotlin
data class Book(val id: Int, val title: String, val coverId: Int)

val book = Book(id = 3, title = "<NAME>", coverId = 254) // Immutable
val modifiedBook = book.copy(coverId = 2) // Copy is a separate immutable instance
```
<!-- .element: class="fragment" data-fragment-index="5" -->

- <div>The value of `book` can not be changed</div>
<!-- .element: class="fragment" data-fragment-index="6" -->
- <div>Creation of `modifiedBook` does not affect the value of book</div>
<!-- .element: class="fragment" data-fragment-index="7" -->
- <div>`modifiedBook` is also immutable</div>
<!-- .element: class="fragment" data-fragment-index="8" -->

%%%

### First-class Functions

- Functions as a **first-class citizen** of the language

- <div>**Higher-order functions**</div> <!-- .element: class="fragment" data-fragment-index="1" -->
  - <div>Functions can **return functions**</div>
<!-- .element: class="fragment" data-fragment-index="2" -->
  - <div>Functions can be **passed as arguments** to other functions</div>
<!-- .element: class="fragment" data-fragment-index="3" -->
  - <div>Functions can be **assigned to variables** and stored inside other data structures</div>
<!-- .element: class="fragment" data-fragment-index="4" -->

- <div>Lambda Expressions</div> <!-- .element: class="fragment" data-fragment-index="5" -->
  - <div>Functions that are **not declared** but **passed immediately** as **an expression**</div>
<!-- .element: class="fragment" data-fragment-index="5" -->

%%%

### Lambda Expressions

- Always **surrounded by curly braces**
- map on List is a higher-order function
- You can pass a lambda expression as the transform function

```kotlin
fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
    val result = arrayListOf<R>()
    for (item in this)
        result.add(transform(item))
    return result
}

val ints = listOf(1, 2, 3)

val doubled = ints.map { value -> value * 2 } // [2, 4, 6]

println(ints.map { it * 3 } ) // [3, 6, 9] - Implicit name for single parameter
```

%%%

<!-- .slide: style="text-align: left;" -->

### Collections <!-- .element: style="text-align: center;" -->

- Kotlin distinguishes **mutable** and **immutable** collections
  - <div>You have control over when collections can be edited</div>
<!-- .element: class="fragment" data-fragment-index="1" -->
  - <div>Helps to eliminate bugs and to design better APIs</div>
<!-- .element: class="fragment" data-fragment-index="2" -->

```kotlin
val ids: List<Int> = listOf(1, 2, 3)
println(ids.get(2)) // 3
ids.add(0, 6) // Unresolved reference: add

val numbers: MutableList<Int> = mutableListOf(5, 9, 3)
numbers.add(0, 6)
println(numbers) // [6, 5, 9, 3]
```
<!-- .element: class="fragment" data-fragment-index="2" -->

- <div>Currently the *immutable* collections are really **read-only versions of mutable collections**</div>
<!-- .element: class="fragment" data-fragment-index="3" -->
- <div>[Immutable Collections Library for Kotlin](https://github.com/Kotlin/kotlinx.collections.immutable)</div>
<!-- .element: class="fragment" data-fragment-index="4" -->
  - <div>Prototypes of real immutable collections with the performance characteristics of typical **FP persistent data structures**</div>
<!-- .element: class="fragment" data-fragment-index="4" -->

%%%

### Functional Combinators

- <NAME>: *A combinator is a function which builds programs fragments from program fragments*
<!-- .element: class="fragment" data-fragment-index="1" -->

- Functional Programming languages usually provide a big set of **combinators for collections**
<!-- .element: class="fragment" data-fragment-index="2" -->

```kotlin
val strings = listOf("Kotlin", "is", "here", "to", "stay")

val result = strings.filter { it.length == 4 }
        .map(String::toUpperCase) // Method reference
        .sortedByDescending { it } // Natural sort order
        .joinToString(separator = " ")

println(result) // STAY HERE
```
<!-- .element: class="fragment" data-fragment-index="3" -->

%%%

### Functional Combinators

```kotlin
val strings = listOf("Kotlin", "is", "here", "to", "stay")

val result: Map<Char, Int> = strings
        .filterNot { it.contains('t') } // Keep only strings without 't'
        .flatMap { it.toList() } // A list of chars from the list of strings
        .groupBy { it } // A map from each char to its occurrences
        .mapValues { it.value.size } // A map from char to occurrence count
        .toList() // List of pairs (char, count)
        .sortedBy { it.second } // Sorted by increasing count

println(result)
// [(i, 1), (s, 1), (h, 1), (r, 1), (e, 2)]

```

---

## with, let, apply

Java

```java
final TextView textView = new TextView(this);
textView.setText("Hello!");
textView.setTextSize(16f);
textView.setTextColor(ContextCompat.getColor(this, android.R.color.white));
```

Kotlin

```kotlin
val textView : TextView = TextView(this)
with(textView) {
    text = ""
    textSize = 16f
    setTextColor(color(android.R.color.white))
}
```

Optional receiver can't be used in this case

---

## with, let, apply

Java

```java
LinearLayout linearLayout = new LinearLayout(this);
if (textView != null) {
    linearLayout.addView(textView);
    setContentView(linearLayout);
}
```

Kotlin

```kotlin
val linearLayout = LinearLayout(this)
textView?.let {
    linearLayout.addView(it)
    setContentView(linearLayout)
}
```

let won't be applied if textView is null

---

## with, let, apply

Java

```java
TextView textView = new TextView(this);
textView.setText("Hello!");
textView.setTextSize(16f);
textView.setTextColor(ContextCompat.getColor(this, android.R.color.white));
```

Kotlin

```kotlin
val textView: TextView = TextView(this).apply {
    text = "Hello!"
    textSize = 16f
    setTextColor(color(android.R.color.white))
}
```

textView can also be optional and this code will still work

---

## Extension functions


- Ability to extend a class with new functionality without inheriting from it
<!-- .element: class="fragment" data-fragment-index="1" -->
- <div>No need to use patterns like **Decorator**</div>
<!-- .element: class="fragment" data-fragment-index="1" -->
- Extension functions do not modify the receiver classes
<!-- .element: class="fragment" data-fragment-index="1" -->
- <div>Excellent substitute to **Helper** methods and **Util** classes</div>
<!-- .element: class="fragment" data-fragment-index="2" -->

---

## Extension functions

- Declared with class name as prefix, then function name

```kotlin
fun Activity.screenWidth(): Int {
    val metrics: DisplayMetrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.widthPixels
}

fun Activity.screenHeight(): Int {
    val metrics: DisplayMetrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.heightPixels
}
```

---

## Extension functions

Then inside my Activity class

```kolin
fun loadImage(url: String) {
    Picasso.with(this)
        .load(url)
        .resize(screenWidth(), 200)
        .into(imageView)
}
```

---

## Kotlin on Android

---

### Kotlin on Android

[anko](https://github.com/Kotlin/anko): Pleasant Android application development

- Huge set of tools to clean and simplify your Android code
- Anko Layouts: **View binding** similar to [ButterKnife's](https://github.com/JakeWharton/butterknife) **@BindView**
- Pleasant **SQLite** management. No need to use an **ORM**
- **async** and **doAsync** to manage asynchronous calls
- Also supports Coroutines (described later)

---

## View binding example

```xml
<Button
        android:id="@+id/btn_start"
        android:layout_width="180dp"
        android:layout_height="180dp"
        android:text="@string/start"
        android:textColor="@color/white"
        android:textSize="20sp" />
```

<div>This widget can be directly accessed using **anko**</div>
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    btn_start.setOnClickListener {
        // Manage button tap here
    }
}
```
<!-- .element: class="fragment" data-fragment-index="1" -->

```kotlin
override fun hideStartButton() {
    btn_start.visibility = INVISIBLE
}
```
<!-- .element: class="fragment" data-fragment-index="1" -->

<div>No need to **findViewById** or similar</div>
<!-- .element: class="fragment" data-fragment-index="2" -->
{'fraction_non_alphanumeric': 0.17267695608709432, 'fraction_numerical': 0.009509180016092458, 'mean_word_length': 3.509510720175921, 'pattern_counts': {'":': 0, '<': 308, '<?xml version=': 0, '>': 314, 'https://': 12, 'lorem ipsum': 0, 'www.': 0, 'xml': 1}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2047477', 'n_tokens_mistral': 13214, 'n_tokens_neox': 12499, 'n_words': 3879}