SlideShare a Scribd company logo
wizeline.com | ademar.oliveira@wizeline.com
КО́ТЛИН
Kotlin
Contents
1. Introduction
2. How to start
3. Basics
a. Package & Import
b. Comments
c. Variables
d. Null Safety
e. Strings
f. Control Flow
i. If - Else
ii. For
iii. When
iv. While
g. Function
h. Higher-Order Functions & Lambda
4. OOP
a. Classes
b. Constructor
c. Properties
d. Methods
e. Inheritance
f. Interfaces
g. Data Classes
5. Ad Libitum
a. Any - Unit - Nothing
b. Let
c. Apply
d. With
e. Collections
i. listOf - mapOf - arrayOf
ii. Operators
f. Extensions
Introduction
Introduction
● Open Source (Apache 2)
● Started 2011; Version 1.0 2016; Currently 1.1.3-2
● Static; Inferred; Script; Functional; OOP
● Platform: JVM; JS; LLVM
● Concise; Safe; Interoperable; Tool-friendly
● Official Android Language
How to start
How to start
● Android Studio 2 Go to:
○ Preferences
○ Plugins
○ Click on Install JetBrains plugin
○ Install Kotlin Language
○ Restart
● Android Studio 3 ready out of the box.
buildscript {
repositories { jcenter() }
dependencies {
classpath "com.android.tools.build:gradle:2.3.3"
}
}
How to start
build.gradle
buildscript {
repositories { jcenter() }
dependencies {
classpath "com.android.tools.build:gradle:2.3.3"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:x.y.z"
}
}
How to start
build.gradle
apply plugin: "com.android.application"
How to start
app/build.gradle
apply plugin: "com.android.application"
apply plugin: "kotlin-android"
// If you're using annotation processor
apply plugin: "kotlin-kapt"
// A pro tip
apply plugin: "kotlin-android-extensions"
How to start
app/build.gradle
dependencies {
annotationProcessor "com.google.dagger:dagger-compiler:2.11"
compile "com.android.support:appcompat-v7:25.3.1"
compile "com.android.support:design:25.3.1"
compile "com.google.dagger:dagger-android:2.11"
testCompile "junit:junit:4.12"
}
How to start
app/build.gradle
dependencies {
kapt "com.google.dagger:dagger-compiler:2.11"
compile "com.android.support:appcompat-v7:25.3.1"
compile "com.android.support:design:25.3.1"
compile "com.google.dagger:dagger-android:2.11"
compile "org.jetbrains.kotlin:kotlin-stdlib:x.y.z"
testCompile "junit:junit:4.12"
}
How to start
app/build.gradle
WIZELINE.COM
You are ready!!!
Basics
Package & Import
Basics
package com.wizeline.academy
import java.io.File
import java.util.*
import android.view.View.GONE
import android.support.v4.content.ContextCompat.getColor
import android.support.v7.app.AppCompatActivity as Activity
Package & Import
Sample.kt
package com.wizeline.academy
import java.io.File
import java.util.*
import android.view.View.GONE
import android.support.v4.content.ContextCompat.getColor
import android.support.v7.app.AppCompatActivity as Activity
Package & Import
Sample.kt
package com.wizeline.academy
import java.io.File
import java.util.*
import android.view.View.GONE
import android.support.v4.content.ContextCompat.getColor
import android.support.v7.app.AppCompatActivity as Activity
Package & Import
Sample.kt
package com.wizeline.academy
import java.io.File
import java.util.*
import android.view.View.GONE
import android.support.v4.content.ContextCompat.getColor
import android.support.v7.app.AppCompatActivity as Activity
Package & Import
Sample.kt
package com.wizeline.academy
import java.io.File
import java.util.*
import android.view.View.GONE
import android.support.v4.content.ContextCompat.getColor
import android.support.v7.app.AppCompatActivity as Activity
Package & Import
Sample.kt
package com.wizeline.academy
import java.io.File
import java.util.*
import android.view.View.GONE
import android.support.v4.content.ContextCompat.getColor
import android.support.v7.app.AppCompatActivity as Activity
Package & Import
Sample.kt
package com.wizeline.academy
import java.io.File
import java.util.*
import android.view.View.GONE
import android.support.v4.content.ContextCompat.getColor
import android.support.v7.app.AppCompatActivity as Activity
Package & Import
Sample.kt
package com.wizeline.academy
import java.io.File
import java.util.*
import android.view.View.GONE
import android.support.v4.content.ContextCompat.getColor
import android.support.v7.app.AppCompatActivity as Activity
Package & Import
Sample.kt
Comments
Basics
// This is an end-of-line comment
/* This is a block comment
on multiple lines. */
/* This is /* a nested comment
on multiple */ lines. */
Package & Import
Sample.kt
Variables
Basics
Val value :
immutable reference
Var variable :
mutable reference
val message: String = "Hello World!"
Variables
Sample.kt
val message: String = "Hello World!"
message = "Bye World!"
Variables
Sample.kt
val message: String = "Hello World!"
message = "Bye World!" // Compile time error, value cannot be assigned
Variables
Sample.kt
var message: String = "Hello World!"
Variables
Sample.kt
var message: String = "Hello World!"
message = "Bye World!"
Variables
Sample.kt
var message: String = "Hello World!"
message = "Bye World!" // It is ok
Variables
Sample.kt
val message: String = "Hello World!"
Variables
Sample.kt
val message = "Hello World!"
Variables
Sample.kt
Null Safety
Basics
var message: String = "Hello World!"
Null Safety
Sample.kt
var message: String = "Hello World!"
message = null
Null Safety
Sample.kt
var message: String = "Hello World!"
message = null // Error: null can not be a value of a non-null type
Null Safety
Sample.kt
var message: String? = "Hello World!"
Null Safety
Sample.kt
var message: String? = "Hello World!"
message = null
Null Safety
Sample.kt
var message: String? = "Hello World!"
message = null // It is ok
Null Safety
Sample.kt
var message: String? = null
Null Safety
Sample.kt
var message: String? = null
message.length
Null Safety
Sample.kt
var message: String? = null
message.length // Error: Only safe or non-null asserted calls are
allowed on a nullable receiver of type String?
Null Safety
Sample.kt
var message: String? = null
message?.length
Null Safety
Sample.kt
var message: String? = null
message?.length // It is ok
Null Safety
Sample.kt
var message: String? = null
message!!.length
Null Safety
Sample.kt
var message: String? = null
message!!.length // Possible but don't do it unless you know what you’re doing
Null Safety
Sample.kt
var message: String? = null
if (message != null) {
message.length // It is ok. Spoiler: if syntax
}
Null Safety
Sample.kt
var message: String? = null
val messageLength = message?.length
println(messageLength) // Spoiler: Print a message to the standard output
Null Safety
Sample.kt
var message: String? = null
val messageLength: Int = message?.length
println(messageLength)
Null Safety
Sample.kt
var message: String? = null
val messageLength: Int = message?.length
// Error: Type mismatch: inferred type is Int? but Int was expected
Null Safety
Sample.kt
var message: String? = null
val messageLength: Int = message?.length ?: 0
println(messageLength)
Null Safety
Sample.kt
Strings
Basics
val message = "Hello World!"
Strings
Sample.kt
val message = "HellotWorld!n"
Strings
Sample.kt
val message = "Hello World!"
val firstLetter: Char = message[0]
Strings
Sample.kt
val message = "Hello World!"
val firstLetter = message[0]
Strings
Sample.kt
val message = "Hello World!"
for (character in message) {
println(character) // Spoiler: for each syntax
}
Strings
Sample.kt
val message = """
Hello
World!
"""
Strings
Sample.kt
val message = """
|Hello
| World!
""".trimMargin()
Strings
Sample.kt
val message = "Hello World!"
val messageLength: Int = message.length
println(message + " length is: " + messageLength)
Strings
Sample.kt
val message = "Hello World!"
val messageLength: Int = message.length
println("$message length is: $messageLength")
Strings
Sample.kt
val message = "Hello World!"
//val messageLength: Int = message.length
println("$message length is: ${message.length}")
Strings
Sample.kt
Control Flow
Basics
IF - ELSE
Control Flow
Basics
val a = random()
val b = random()
Control Flow - If else
Sample.kt
val a = random()
val b = random()
if (a > b) {
println("A is greater than b.")
}
Control Flow - If else
Sample.kt
val a = random()
val b = random()
if (a > b) {
println("A is greater than b.")
} else {
println("A is not greater than b.")
}
Control Flow - If else
Sample.kt
val a = random()
val b = random()
if (a > b) {
println("A is greater than b.")
} else if (a == b) {
println("A is equal to b.")
} else {
println("A is less than b.")
}
Control Flow - If else
Sample.kt
For
Control Flow
Basics
val message = "Hello World!"
for (character in message) {
println(character)
}
Control Flow - For
Sample.kt
for (number: Int in 0..10) {
println(number)
}
Control Flow - For
Sample.kt
for (number in 0..10) {
println(number)
}
Control Flow - For
Sample.kt
for (number in 0..10) {
println(number)
}
// Prints 0, 1, ..., 10
Control Flow - For
Sample.kt
for (number in 0 until 10) {
println(number)
}
Control Flow - For
Sample.kt
for (number in 0 until 10) {
println(number)
}
// Prints 0, 1, ..., 9
Control Flow - For
Sample.kt
for (number in 0..10 step 3) {
println(number)
}
Control Flow - For
Sample.kt
for (number in 0..10 step 3) {
println(number)
}
// Prints 0, 3, 6, 9
Control Flow - For
Sample.kt
for (number in 10 downTo 0) {
println(number)
}
Control Flow - For
Sample.kt
for (number in 10 downTo 0) {
println(number)
}
// Prints 10, 9, ..., 0
Control Flow - For
Sample.kt
val array: Array<String> = arrayOf<String>("Hello", "World!")
// Spoiler: How to create an array
Control Flow - For
Sample.kt
val array = arrayOf("Hello", "World!")
// Spoiler: How to create an array
Control Flow - For
Sample.kt
val array = arrayOf("Hello", "World!")
for (item: String in array) {
println(item)
}
Control Flow - For
Sample.kt
val array = arrayOf("Hello", "World!")
for (item in array) {
println(item)
}
Control Flow - For
Sample.kt
val array = arrayOf("Hello", "World!")
for (item in array) {
println(item)
}
// Prints Hello and World!
Control Flow - For
Sample.kt
val array = arrayOf("Hello", "World!")
for ((index, item) in array.withIndex()) { // Spoiler: Destructuring syntax
println("$index $item")
}
Control Flow - For
Sample.kt
val array = arrayOf("Hello", "World!")
for ((index, item) in array.withIndex()) {
println("$index $item")
}
// Prints 0 Hello and 1 World!
Control Flow - For
Sample.kt
When
Control Flow
Basics
val clumpsOfSugar = 0
when (clumpsOfSugar) {
0 -> println("The right way to drink coffee")
1 -> println("It is a sin, but I can ignore")
else -> {
println("Wait, $clumpsOfSugar clumps of sugar!?")
println("It is an unforgivable sin!!!")
}
}
Control Flow - When
Sample.kt
val clumpsOfSugar = 0
when (clumpsOfSugar) {
0 -> println("The right way to drink coffee")
1 -> println("It is a sin, but I can ignore")
else -> {
println("Wait, $clumpsOfSugar clumps of sugar!?")
println("It is an unforgivable sin!!!")
}
}
Control Flow - When
Sample.kt
val clumpsOfSugar = 0
when (clumpsOfSugar) {
0 -> println("The right way to drink coffee")
1, 2 -> println("It is a sin, but I can ignore")
else -> {
println("Wait, $clumpsOfSugar clumps of sugar!?")
println("It is an unforgivable sin!!!")
}
}
Control Flow - When
Sample.kt
val clumpsOfSugar = 0
when (clumpsOfSugar) {
0 -> println("The right way to drink coffee")
1, 2 -> println("It is a sin, but I can ignore")
in 3..5 -> println("Is it a kind of candy???")
else -> {
println("Wait, $clumpsOfSugar clumps of sugar!?")
println("It is an unforgivable sin!!!")
}
}
Control Flow - When
Sample.kt
val clumpsOfSugar = 0
when (clumpsOfSugar) {
0 -> println("The right way to drink coffee")
1, 2 -> println("It is a sin, but I can ignore")
!in 3..5 -> println("It is not 3, 4 or 5 :)")
else -> {
println("Wait, $clumpsOfSugar clumps of sugar!?")
println("It is an unforgivable sin!!!")
}
}
Control Flow - When
Sample.kt
val clumpsOfSugar = 0
val candyNumbers = arrayOf(3, 4, 5)
when (clumpsOfSugar) {
0 -> println("The right way to drink coffee")
1, 2 -> println("It is a sin, but I can ignore")
in candyNumbers -> println("Is it a kind of candy???")
else -> {
println("Wait, $clumpsOfSugar clumps of sugar!?")
println("It is an unforgivable sin!!!")
}
}
Control Flow - When
Sample.kt
val clumpsOfSugar = 0
when (clumpsOfSugar) {
0 -> println("The right way to drink coffee")
1, 2 -> println("It is a sin, but I can ignore")
randomInt() -> println("Are we still talking about coffee?")
else -> {
println("Wait, $clumpsOfSugar clumps of sugar!?")
println("It is an unforgivable sin!!!")
}
}
Control Flow - When
Sample.kt
val clumpsOfSugar = 0
when {
clumpsOfSugar % 2 == 1 -> println("An odd amount of sugar clumps")
clumpsOfSugar % 2 == 0 -> println("An even amount of sugar clumps")
else -> println("We have a really strange amount of sugar clumps")
}
Control Flow - When
Sample.kt
val clumpsOfSugar = 0
when {
clumpsOfSugar.isOdd() -> println("An odd amount of sugar clumps")
clumpsOfSugar.isEven() -> println("An even amount of sugar clumps")
else -> println("We have a really strange amount of sugar clumps")
}
Control Flow - When
Sample.kt
While
Control Flow
Basics
var clumpsOfSugar = 10
while (clumpsOfSugar > 0) {
clumpsOfSugar-- // yes we have -- and ++ syntax
}
println(clumpsOfSugar) // Prints 0
Control Flow - While
Sample.kt
var clumpsOfSugar = 10
do {
clumpsOfSugar--
} while (clumpsOfSugar > 0)
println(clumpsOfSugar) // Prints 0
Control Flow - While
Sample.kt
Function
Basics
fun sayHelloWorld() {
println("Hello World")
}
Function
Sample.kt
fun sayHelloWorld() = println("Hello World")
Function
Sample.kt
fun say(message: String) {
println(message)
}
Function
Sample.kt
fun say(message: String = "Hello World") {
println(message)
}
Function
Sample.kt
fun sum(a: Int, b: Int): Int {
return a + b
}
Function
Sample.kt
fun sum(a: Int, b: Int): Int = a + b
Function
Sample.kt
fun sum(a: Int, b: Int) = a + b
Function
Sample.kt
fun makeCoffee(
milliliters: Int,
concentration: Float,
useSugar: Boolean = false) {
// make your coffee
}
Function
Sample.kt
fun makeCoffee(
milliliters: Int,
concentration: Float,
useSugar: Boolean = false) {
// make your coffee
}
Function
Sample.kt
fun makeCoffee(
milliliters: Int,
concentration: Float,
useSugar: Boolean = false) {
// make your coffee
}
makeCoffee(200, 0.8f)
Function
Sample.kt
fun makeCoffee(
milliliters: Int,
concentration: Float,
useSugar: Boolean = false) {
// make your coffee
}
makeCoffee(200, 0.8f, true)
Function
Sample.kt
fun makeCoffee(
milliliters: Int,
concentration: Float,
useSugar: Boolean = false) {
// make your coffee
}
makeCoffee(200, 0.8f, useSugar = true)
Function
Sample.kt
fun makeCoffee(
milliliters: Int,
concentration: Float,
useSugar: Boolean = false) {
// make your coffee
}
makeCoffee(milliliters = 200, concentration = 0.8f, useSugar = true)
Function
Sample.kt
fun makeCoffee(
milliliters: Int,
concentration: Float,
useSugar: Boolean = false) {
// make your coffee
}
makeCoffee(useSugar = true, milliliters = 200, concentration = 0.8f)
Function
Sample.kt
fun outside() {
fun inside() {
// Do something
}
// ...
inside() // we can call in this scope
// ...
}
Function
Sample.kt
Higher-Order Functions & Lambda
Basics
// Java on click listener
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// Do something
}
});
Higher-Order Functions & Lambda
Sample.kt
// Java 8 on click listener with lambda
setOnClickListener(view -> {
// Do something
});
Higher-Order Functions & Lambda
Sample.kt
// Kotlin on click listener with lambda
setOnClickListener {
// Do something
}
Higher-Order Functions & Lambda
Sample.kt
fun sum(a: Int, b: Int, callback: (Int) -> Unit) { // Spoiler: Unit type
val summed = a + b
callback(summed)
}
Higher-Order Functions & Lambda
Sample.kt
fun sum(a: Int, b: Int, callback: (Int) -> Unit) {
val summed = a + b
callback(summed)
}
Higher-Order Functions & Lambda
Sample.kt
fun sum(a: Int, b: Int, callback: (Int) -> Unit) {
val summed = a + b
callback(summed)
}
sum(1, 2) { result ->
println(result) // prints 3
}
Higher-Order Functions & Lambda
Sample.kt
fun sum(a: Int, b: Int, callback: (Int) -> Unit) {
val summed = a + b
callback(summed)
}
sum(1, 2) {
println(it) // Also prints 3
}
Higher-Order Functions & Lambda
Sample.kt
val sum: (Int, Int) -> Int = { x: Int, y: Int ->
x + y
}
Higher-Order Functions & Lambda
Sample.kt
val sum: (Int, Int) -> Int = { x: Int, y: Int -> x + y }
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
calculation(3, 2, sum)
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
calculation(3, 2, sum) // returns 5
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
calculation(3, 2, sum)
calculation(3, 2, sub)
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
calculation(3, 2, sum)
calculation(3, 2, sub) // returns 1
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
calculation(3, 2, sum)
calculation(3, 2, sub)
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
calculation(3, 2, { x, y ->
x * y
})
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
calculation(3, 2, { x, y ->
x * y
}) // returns 6
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
calculation(3, 2) { x, y ->
x * y
}
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
calculation(3, 2) { x, y -> x * y }
Higher-Order Functions & Lambda
Sample.kt
val sum = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x - y }
fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int {
return rule(a, b)
}
fun sum(a: Int, b: Int) = a + b
calculation(3, 2, ::sum)
Higher-Order Functions & Lambda
Sample.kt
OOP
Classes
OOP
class Coffee {
}
Classes
Coffee.kt
class Coffee
Classes
Coffee.kt
class Coffee
val coffee = Coffee()
Classes
Coffee.kt
Constructor
OOP
class Coffee(type: String)
Constructor
Coffee.kt
class Coffee constructor(type: String)
Constructor
Coffee.kt
class Coffee @Inject constructor(type: String)
Constructor
Coffee.kt
class CustomView : View { // Spoiler: Inheritance
constructor(c: Context) : super(c) {}
constructor(c: Context, a: AttributeSet?) : super(c, a) {}
constructor(c: Context, a: AttributeSet?, d: Int) : super(c, a, d) {}
constructor(c: Context, a: AttributeSet?, d: Int, r: Int) : super(c, a, d, r) {}
}
Constructor
CustomView.kt
class Coffee(type: String)
Constructor
Coffee.kt
class Coffee(type: String)
class Coffee(var type: String)
Constructor
Coffee.kt
class Coffee(type: String)
class Coffee(var type: String)
class Coffee(val type: String)
Constructor
Coffee.kt
class Coffee(type: String)
class Coffee(var type: String)
class Coffee(val type: String)
class Coffee(private val type: String)
Constructor
Coffee.kt
class Coffee(type: String)
class Coffee(var type: String)
class Coffee(val type: String)
class Coffee(private val type: String)
class Coffee(private val type: String = "Espresso")
Constructor
Coffee.kt
class Coffee(type: String) {
private val name = "Coffee $type"
}
Constructor
Coffee.kt
class Coffee(type: String) {
private val name: String
init {
name = "Coffee $type"
}
}
Constructor
Coffee.kt
class Coffee {
private val name: String
constructor(type: String) {
name = "Coffee $type"
}
}
Constructor
Coffee.kt
class Coffee(val type: String) {
}
Constructor
Coffee.kt
Properties
OOP
class Coffee {
val type = "Espresso"
var drinked = false
private val gourmet = true
}
Properties
Coffee.kt
class Coffee {
var type = "Espresso"
get() {
return field
}
set(value) {
field = value
}
}
Properties
Coffee.kt
class Coffee(context: Context) {
private val preferences = context.getSharedPreferences("Coffee", MODE_PRIVATE)
var type
get() = preferences.getString("TypeKey", "Default")
set(value) {
preferences.edit().putString("TypeKey", value).apply()
}
}
Properties
Coffee.kt
class Coffee {
var type = "Espresso"
private set
}
Properties
Coffee.kt
class Coffee {
lateinit var type: String
}
Properties
Coffee.kt
class Coffee {
@JsonField lateinit var type: String
}
Properties
Coffee.kt
class Coffee {
val type: String by lazy {
println("You are running this code!")
"Hello"
}
val x = type
val y = type
}
Properties
Coffee.kt
class Coffee {
val type: String by lazy {
println("You are running this code!")
"Hello"
}
val x = type // It prints "You are running this code!" 1 time
val y = type // It don't prints anything
}
Properties
Coffee.kt
Methods
OOP
Kotlin methods are functions,
and you already know it.
Inheritance
OOP
open class Coffee
class Cappuccino : Coffee()
Inheritance
Coffee.kt
open class Coffee(type: String)
class Cappuccino : Coffee("Cappuccino")
Inheritance
Coffee.kt
open class Coffee(type: String)
class Cappuccino(type: String) : Coffee(type)
Inheritance
Coffee.kt
open class Coffee {
constructor(type: String)
constructor(type: String, temperature: Float)
}
class Cappuccino : Coffee {
constructor(type: String) : super(type)
constructor(type: String, temperature: Float) : super(type, temperature)
}
Inheritance
Coffee.kt
open class Coffee {
open fun drink() {
println("So tasty")
}
}
class Cappuccino : Coffee() {
override fun drink() {
super.drink()
}
}
Inheritance
Coffee.kt
Interfaces
OOP
interface Drinkable
class Coffee : Drinkable
Interfaces
Coffee.kt
interface Drinkable {
fun drink()
}
class Coffee : Drinkable {
override fun drink() {
println("So tasty")
}
}
Interfaces
Coffee.kt
interface Drinkable {
fun drink() {
println("So tasty")
}
}
class Coffee : Drinkable
Interfaces
Coffee.kt
interface Drinkable {
val type: String
}
class Coffee : Drinkable {
override val type = "Coffee"
}
Interfaces
Coffee.kt
open class Coffee
interface Drinkable {
fun drink()
}
class Cappuccino : Coffee(), Drinkable {
override fun drink() {
println("So tasty")
}
}
Interfaces
Coffee.kt
open class Coffee {
open fun drink() = println("So coffee")
}
interface Drinkable {
fun drink() = println("So tasty")
}
class Cappuccino : Coffee(), Drinkable {
// What happens here ?
}
Interfaces
Coffee.kt
open class Coffee {
open fun drink() = println("So coffee")
}
interface Drinkable {
fun drink() = println("So tasty")
}
class Cappuccino : Coffee(), Drinkable {
override fun drink() {
super<Coffee>.drink()
super<Drinkable>.drink()
}
}
Interfaces
Coffee.kt
Data Classes
OOP
data class Coffee(val type: String)
Data Classes
Coffee.kt
data class Coffee(val type: String)
val a = Coffee("Cappuccino")
val b = Coffee("Cappuccino")
println(a == b) // Prints true
Data Classes - Equals & HashCode
Coffee.kt
data class Coffee(val type: String)
val a = Coffee("Cappuccino")
val b = Coffee("Ristretto")
println(a == b) // Prints false
Data Classes - Equals & HashCode
Coffee.kt
data class Coffee(val type: String)
val a = Coffee("Cappuccino")
println(a.toString()) // Prints: Coffee(type=Cappuccino)
Data Classes - toString()
Coffee.kt
data class Coffee(val type: String)
val a = Coffee("Cappuccino")
val b = a.copy()
Data Classes - copy
Coffee.kt
data class Coffee(val type: String)
val a = Coffee("Cappuccino")
val b = a.copy()
val c = a.copy(type = "Ristretto")
Data Classes - copy
Coffee.kt
Ad Libitum
SKIP
Any - Unit - Nothing
Ad Libitum
Any
Any
StringCoffee
Unit
Any
StringCoffee
Any? Unit
Any
Coffee String
Any? Unit
Any
Coffee
Coffee? String? Unit?
String
Any? Unit
Any
Coffee
Coffee? String? Unit?
Nothing?
String
Any? Unit
Any
Coffee
Coffee? String? Unit?
Nothing?
Nothing
String
Let
Ad Libitum
val message = "Hello World"
message.let {
println(it)
}
// prints: Hello World
Let
Sample.kt
val message: String? = "Hello World"
message?.let {
println(it)
}
// prints: Hello World
Let
Sample.kt
val message: String? = null
message?.let {
println(it)
}
// Don't print anything
Let
Sample.kt
Apply
Ad Libitum
val textView = TextView(context)
textView.layoutParams = LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
textView.textSize = context.resources.getDimension(R.dimen.text_size)
textView.setTextColor(Color.RED)
textView.text = "Hello World!"
Apply
Sample.kt
val textView = TextView(context).apply {
layoutParams = LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
textSize = context.resources.getDimension(R.dimen.text_size)
setTextColor(Color.RED)
text = "Hello World!"
}
Apply
Sample.kt
With
Ad Libitum
val textView = TextView(context)
textView.layoutParams = LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
textView.textSize = context.resources.getDimension(R.dimen.text_size)
textView.setTextColor(Color.RED)
textView.text = "Hello World!"
With
Sample.kt
val textView = TextView(context)
with(textView) {
layoutParams = LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
textSize = context.resources.getDimension(R.dimen.text_size)
setTextColor(Color.RED)
text = "Hello World!"
}
With
Sample.kt
Collections
Ad Libitum
listOf - mapOf - <type>ArrayOf
Collections
Ad Libitum
val anEmptyList = listOf<String>()
val anInferedTypeList = listOf("Hello", "World")
val anIntegerList = listOf<Int>()
val anotherInferedTypeList = listOf(1, 2, 3)
Collections - listOf
Sample.kt
val aPrimitiveIntArray = intArrayOf(1, 2, 3)
val aPrimitiveByteArray = byteArrayOf()
val aPrimitiveBooleanArray = booleanArrayOf()
Collections - <type>ArrayOf
Sample.kt
val aMap = mapOf<String, Boolean>()
val aInferedMap = mapOf(Pair("Key-A", true), Pair("Key-B", false))
val aHashMap = hashMapOf<String, Int>()
val alinkedMap = linkedMapOf<String, Any>()
Collections - mapOf
Sample.kt
Operators
Collections
Ad Libitum
listOf(1, 2, 3, 4, 5)
.forEach { item ->
println(item)
}
// Prints 1, 2, 3, 4 and 5
Collections - Operators - Foreach
Sample.kt
listOf(1, 2, 3, 4, 5)
.forEach {
println(it)
}
// Prints 1, 2, 3, 4 and 5
Collections - Operators - Foreach
Sample.kt
listOf("Hello", "World")
.forEachIndexed { index, item ->
println("Item $item at index $index")
}
// Prints: Item Hello at index 0 and Item World at index 1
Collections - Operators - Filter
Sample.kt
listOf(1, 2, 3, 4, 5)
.map { it * 2 }
.forEach { println(it) }
// Prints 2, 4, 6, 8 and 10
Collections - Operators - Map
Sample.kt
listOf(5, 3, 1, 4, 2)
.sortedBy { it }
.forEach { println(it) }
// Prints 1, 2, 3, 4 and 5
Collections - Operators - Sort
Sample.kt
listOf(1, 2, 3, 4, 5)
.filter { it > 2 }
.forEach { print(it) }
// Prints: 3, 4 and 5
Collections - Operators - Filter
Sample.kt
Extensions
Ad Libitum
fun ViewGroup.inflate(layout: Int, attachToRoot: Boolean = true): View {
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(layout, this, attachToRoot)
return view
}
// Use it
someViewGroup.inflate(R.layout.item)
Extensions
Sample.kt
SLIDE
228
Now this is not the end. It is not even the
beginning of the end. But it is, perhaps,
the end of the beginning.
ademar.oliveira@wizeline.com
THANK
YOU

More Related Content

What's hot

Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingaprilyyy
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingChaAstillas
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)jewelyngrace
 
What is to loop in c++
What is to loop in c++What is to loop in c++
What is to loop in c++
03446940736
 
Algorithm and Programming (Branching Structure)
Algorithm and Programming (Branching Structure)Algorithm and Programming (Branching Structure)
Algorithm and Programming (Branching Structure)
Adam Mukharil Bachtiar
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programming
Eric Polerecky
 
Refactoring a go project
Refactoring a go projectRefactoring a go project
Refactoring a go project
Dan Tran
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
Rodolfo Carvalho
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for Scala
Knoldus Inc.
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
tanmaymodi4
 
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' RequestChecking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
PVS-Studio
 
Critical errors in CryEngine V code
Critical errors in CryEngine V codeCritical errors in CryEngine V code
Critical errors in CryEngine V code
PVS-Studio
 
Brief analysis of Media Portal 2 bugs
Brief analysis of Media Portal 2 bugsBrief analysis of Media Portal 2 bugs
Brief analysis of Media Portal 2 bugs
PVS-Studio
 
Checking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-StudioChecking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-Studio
Andrey Karpov
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
Carson Wilber
 
Perl Tidy Perl Critic
Perl Tidy Perl CriticPerl Tidy Perl Critic
Perl Tidy Perl Critic
olegmmiller
 
Dusting the globe: analysis of NASA World Wind project
Dusting the globe: analysis of NASA World Wind projectDusting the globe: analysis of NASA World Wind project
Dusting the globe: analysis of NASA World Wind project
PVS-Studio
 
Analyzing ReactOS One More Time
Analyzing ReactOS One More TimeAnalyzing ReactOS One More Time
Analyzing ReactOS One More Time
PVS-Studio
 
Legacy Code Kata v3.0
Legacy Code Kata v3.0Legacy Code Kata v3.0
Legacy Code Kata v3.0
William Munn
 

What's hot (20)

Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)
 
What is to loop in c++
What is to loop in c++What is to loop in c++
What is to loop in c++
 
Algorithm and Programming (Branching Structure)
Algorithm and Programming (Branching Structure)Algorithm and Programming (Branching Structure)
Algorithm and Programming (Branching Structure)
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programming
 
Refactoring a go project
Refactoring a go projectRefactoring a go project
Refactoring a go project
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for Scala
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' RequestChecking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
 
Critical errors in CryEngine V code
Critical errors in CryEngine V codeCritical errors in CryEngine V code
Critical errors in CryEngine V code
 
Os2
Os2Os2
Os2
 
Brief analysis of Media Portal 2 bugs
Brief analysis of Media Portal 2 bugsBrief analysis of Media Portal 2 bugs
Brief analysis of Media Portal 2 bugs
 
Checking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-StudioChecking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-Studio
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 
Perl Tidy Perl Critic
Perl Tidy Perl CriticPerl Tidy Perl Critic
Perl Tidy Perl Critic
 
Dusting the globe: analysis of NASA World Wind project
Dusting the globe: analysis of NASA World Wind projectDusting the globe: analysis of NASA World Wind project
Dusting the globe: analysis of NASA World Wind project
 
Analyzing ReactOS One More Time
Analyzing ReactOS One More TimeAnalyzing ReactOS One More Time
Analyzing ReactOS One More Time
 
Legacy Code Kata v3.0
Legacy Code Kata v3.0Legacy Code Kata v3.0
Legacy Code Kata v3.0
 

Similar to Kotlin

Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrains
Jigar Gosar
 
Start with swift
Start with swiftStart with swift
Kotlin fundamentals - By: Ipan Ardian
Kotlin fundamentals - By: Ipan ArdianKotlin fundamentals - By: Ipan Ardian
Kotlin fundamentals - By: Ipan Ardian
Rizal Khilman
 
Kotlin Fundamentals
Kotlin Fundamentals Kotlin Fundamentals
Kotlin Fundamentals
Ipan Ardian
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
Mohamed Wael
 
Swift, swiftly
Swift, swiftlySwift, swiftly
Swift, swiftly
Jack Nutting
 
Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
Vincent Pradeilles
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercises(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercises
Nico Ludwig
 
A First Date With Scala
A First Date With ScalaA First Date With Scala
A First Date With Scala
Franco Lombardo
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
Olve Maudal
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
apidays
 
ParaSail
ParaSail  ParaSail
ParaSail
AdaCore
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
PVS-Studio
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
PVS-Studio
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Java Basics 1.pptx
Java Basics 1.pptxJava Basics 1.pptx
Java Basics 1.pptx
TouseeqHaider11
 
An Introduction to Property Based Testing
An Introduction to Property Based TestingAn Introduction to Property Based Testing
An Introduction to Property Based Testing
C4Media
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Abhijeet Dubey
 

Similar to Kotlin (20)

Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrains
 
Start with swift
Start with swiftStart with swift
Start with swift
 
Kotlin fundamentals - By: Ipan Ardian
Kotlin fundamentals - By: Ipan ArdianKotlin fundamentals - By: Ipan Ardian
Kotlin fundamentals - By: Ipan Ardian
 
Kotlin Fundamentals
Kotlin Fundamentals Kotlin Fundamentals
Kotlin Fundamentals
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
 
Swift, swiftly
Swift, swiftlySwift, swiftly
Swift, swiftly
 
Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercises(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercises
 
A First Date With Scala
A First Date With ScalaA First Date With Scala
A First Date With Scala
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
 
ParaSail
ParaSail  ParaSail
ParaSail
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Java Basics 1.pptx
Java Basics 1.pptxJava Basics 1.pptx
Java Basics 1.pptx
 
An Introduction to Property Based Testing
An Introduction to Property Based TestingAn Introduction to Property Based Testing
An Introduction to Property Based Testing
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 

Recently uploaded

Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 

Recently uploaded (20)

Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 

Kotlin

  • 2. Contents 1. Introduction 2. How to start 3. Basics a. Package & Import b. Comments c. Variables d. Null Safety e. Strings f. Control Flow i. If - Else ii. For iii. When iv. While g. Function h. Higher-Order Functions & Lambda 4. OOP a. Classes b. Constructor c. Properties d. Methods e. Inheritance f. Interfaces g. Data Classes 5. Ad Libitum a. Any - Unit - Nothing b. Let c. Apply d. With e. Collections i. listOf - mapOf - arrayOf ii. Operators f. Extensions
  • 4. Introduction ● Open Source (Apache 2) ● Started 2011; Version 1.0 2016; Currently 1.1.3-2 ● Static; Inferred; Script; Functional; OOP ● Platform: JVM; JS; LLVM ● Concise; Safe; Interoperable; Tool-friendly ● Official Android Language
  • 6. How to start ● Android Studio 2 Go to: ○ Preferences ○ Plugins ○ Click on Install JetBrains plugin ○ Install Kotlin Language ○ Restart ● Android Studio 3 ready out of the box.
  • 7. buildscript { repositories { jcenter() } dependencies { classpath "com.android.tools.build:gradle:2.3.3" } } How to start build.gradle
  • 8. buildscript { repositories { jcenter() } dependencies { classpath "com.android.tools.build:gradle:2.3.3" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:x.y.z" } } How to start build.gradle
  • 10. apply plugin: "com.android.application" apply plugin: "kotlin-android" // If you're using annotation processor apply plugin: "kotlin-kapt" // A pro tip apply plugin: "kotlin-android-extensions" How to start app/build.gradle
  • 11. dependencies { annotationProcessor "com.google.dagger:dagger-compiler:2.11" compile "com.android.support:appcompat-v7:25.3.1" compile "com.android.support:design:25.3.1" compile "com.google.dagger:dagger-android:2.11" testCompile "junit:junit:4.12" } How to start app/build.gradle
  • 12. dependencies { kapt "com.google.dagger:dagger-compiler:2.11" compile "com.android.support:appcompat-v7:25.3.1" compile "com.android.support:design:25.3.1" compile "com.google.dagger:dagger-android:2.11" compile "org.jetbrains.kotlin:kotlin-stdlib:x.y.z" testCompile "junit:junit:4.12" } How to start app/build.gradle
  • 16. package com.wizeline.academy import java.io.File import java.util.* import android.view.View.GONE import android.support.v4.content.ContextCompat.getColor import android.support.v7.app.AppCompatActivity as Activity Package & Import Sample.kt
  • 17. package com.wizeline.academy import java.io.File import java.util.* import android.view.View.GONE import android.support.v4.content.ContextCompat.getColor import android.support.v7.app.AppCompatActivity as Activity Package & Import Sample.kt
  • 18. package com.wizeline.academy import java.io.File import java.util.* import android.view.View.GONE import android.support.v4.content.ContextCompat.getColor import android.support.v7.app.AppCompatActivity as Activity Package & Import Sample.kt
  • 19. package com.wizeline.academy import java.io.File import java.util.* import android.view.View.GONE import android.support.v4.content.ContextCompat.getColor import android.support.v7.app.AppCompatActivity as Activity Package & Import Sample.kt
  • 20. package com.wizeline.academy import java.io.File import java.util.* import android.view.View.GONE import android.support.v4.content.ContextCompat.getColor import android.support.v7.app.AppCompatActivity as Activity Package & Import Sample.kt
  • 21. package com.wizeline.academy import java.io.File import java.util.* import android.view.View.GONE import android.support.v4.content.ContextCompat.getColor import android.support.v7.app.AppCompatActivity as Activity Package & Import Sample.kt
  • 22. package com.wizeline.academy import java.io.File import java.util.* import android.view.View.GONE import android.support.v4.content.ContextCompat.getColor import android.support.v7.app.AppCompatActivity as Activity Package & Import Sample.kt
  • 23. package com.wizeline.academy import java.io.File import java.util.* import android.view.View.GONE import android.support.v4.content.ContextCompat.getColor import android.support.v7.app.AppCompatActivity as Activity Package & Import Sample.kt
  • 25. // This is an end-of-line comment /* This is a block comment on multiple lines. */ /* This is /* a nested comment on multiple */ lines. */ Package & Import Sample.kt
  • 27. Val value : immutable reference Var variable : mutable reference
  • 28. val message: String = "Hello World!" Variables Sample.kt
  • 29. val message: String = "Hello World!" message = "Bye World!" Variables Sample.kt
  • 30. val message: String = "Hello World!" message = "Bye World!" // Compile time error, value cannot be assigned Variables Sample.kt
  • 31. var message: String = "Hello World!" Variables Sample.kt
  • 32. var message: String = "Hello World!" message = "Bye World!" Variables Sample.kt
  • 33. var message: String = "Hello World!" message = "Bye World!" // It is ok Variables Sample.kt
  • 34. val message: String = "Hello World!" Variables Sample.kt
  • 35. val message = "Hello World!" Variables Sample.kt
  • 37. var message: String = "Hello World!" Null Safety Sample.kt
  • 38. var message: String = "Hello World!" message = null Null Safety Sample.kt
  • 39. var message: String = "Hello World!" message = null // Error: null can not be a value of a non-null type Null Safety Sample.kt
  • 40. var message: String? = "Hello World!" Null Safety Sample.kt
  • 41. var message: String? = "Hello World!" message = null Null Safety Sample.kt
  • 42. var message: String? = "Hello World!" message = null // It is ok Null Safety Sample.kt
  • 43. var message: String? = null Null Safety Sample.kt
  • 44. var message: String? = null message.length Null Safety Sample.kt
  • 45. var message: String? = null message.length // Error: Only safe or non-null asserted calls are allowed on a nullable receiver of type String? Null Safety Sample.kt
  • 46. var message: String? = null message?.length Null Safety Sample.kt
  • 47. var message: String? = null message?.length // It is ok Null Safety Sample.kt
  • 48. var message: String? = null message!!.length Null Safety Sample.kt
  • 49. var message: String? = null message!!.length // Possible but don't do it unless you know what you’re doing Null Safety Sample.kt
  • 50. var message: String? = null if (message != null) { message.length // It is ok. Spoiler: if syntax } Null Safety Sample.kt
  • 51. var message: String? = null val messageLength = message?.length println(messageLength) // Spoiler: Print a message to the standard output Null Safety Sample.kt
  • 52. var message: String? = null val messageLength: Int = message?.length println(messageLength) Null Safety Sample.kt
  • 53. var message: String? = null val messageLength: Int = message?.length // Error: Type mismatch: inferred type is Int? but Int was expected Null Safety Sample.kt
  • 54. var message: String? = null val messageLength: Int = message?.length ?: 0 println(messageLength) Null Safety Sample.kt
  • 56. val message = "Hello World!" Strings Sample.kt
  • 57. val message = "HellotWorld!n" Strings Sample.kt
  • 58. val message = "Hello World!" val firstLetter: Char = message[0] Strings Sample.kt
  • 59. val message = "Hello World!" val firstLetter = message[0] Strings Sample.kt
  • 60. val message = "Hello World!" for (character in message) { println(character) // Spoiler: for each syntax } Strings Sample.kt
  • 61. val message = """ Hello World! """ Strings Sample.kt
  • 62. val message = """ |Hello | World! """.trimMargin() Strings Sample.kt
  • 63. val message = "Hello World!" val messageLength: Int = message.length println(message + " length is: " + messageLength) Strings Sample.kt
  • 64. val message = "Hello World!" val messageLength: Int = message.length println("$message length is: $messageLength") Strings Sample.kt
  • 65. val message = "Hello World!" //val messageLength: Int = message.length println("$message length is: ${message.length}") Strings Sample.kt
  • 67. IF - ELSE Control Flow Basics
  • 68. val a = random() val b = random() Control Flow - If else Sample.kt
  • 69. val a = random() val b = random() if (a > b) { println("A is greater than b.") } Control Flow - If else Sample.kt
  • 70. val a = random() val b = random() if (a > b) { println("A is greater than b.") } else { println("A is not greater than b.") } Control Flow - If else Sample.kt
  • 71. val a = random() val b = random() if (a > b) { println("A is greater than b.") } else if (a == b) { println("A is equal to b.") } else { println("A is less than b.") } Control Flow - If else Sample.kt
  • 73. val message = "Hello World!" for (character in message) { println(character) } Control Flow - For Sample.kt
  • 74. for (number: Int in 0..10) { println(number) } Control Flow - For Sample.kt
  • 75. for (number in 0..10) { println(number) } Control Flow - For Sample.kt
  • 76. for (number in 0..10) { println(number) } // Prints 0, 1, ..., 10 Control Flow - For Sample.kt
  • 77. for (number in 0 until 10) { println(number) } Control Flow - For Sample.kt
  • 78. for (number in 0 until 10) { println(number) } // Prints 0, 1, ..., 9 Control Flow - For Sample.kt
  • 79. for (number in 0..10 step 3) { println(number) } Control Flow - For Sample.kt
  • 80. for (number in 0..10 step 3) { println(number) } // Prints 0, 3, 6, 9 Control Flow - For Sample.kt
  • 81. for (number in 10 downTo 0) { println(number) } Control Flow - For Sample.kt
  • 82. for (number in 10 downTo 0) { println(number) } // Prints 10, 9, ..., 0 Control Flow - For Sample.kt
  • 83. val array: Array<String> = arrayOf<String>("Hello", "World!") // Spoiler: How to create an array Control Flow - For Sample.kt
  • 84. val array = arrayOf("Hello", "World!") // Spoiler: How to create an array Control Flow - For Sample.kt
  • 85. val array = arrayOf("Hello", "World!") for (item: String in array) { println(item) } Control Flow - For Sample.kt
  • 86. val array = arrayOf("Hello", "World!") for (item in array) { println(item) } Control Flow - For Sample.kt
  • 87. val array = arrayOf("Hello", "World!") for (item in array) { println(item) } // Prints Hello and World! Control Flow - For Sample.kt
  • 88. val array = arrayOf("Hello", "World!") for ((index, item) in array.withIndex()) { // Spoiler: Destructuring syntax println("$index $item") } Control Flow - For Sample.kt
  • 89. val array = arrayOf("Hello", "World!") for ((index, item) in array.withIndex()) { println("$index $item") } // Prints 0 Hello and 1 World! Control Flow - For Sample.kt
  • 91. val clumpsOfSugar = 0 when (clumpsOfSugar) { 0 -> println("The right way to drink coffee") 1 -> println("It is a sin, but I can ignore") else -> { println("Wait, $clumpsOfSugar clumps of sugar!?") println("It is an unforgivable sin!!!") } } Control Flow - When Sample.kt
  • 92. val clumpsOfSugar = 0 when (clumpsOfSugar) { 0 -> println("The right way to drink coffee") 1 -> println("It is a sin, but I can ignore") else -> { println("Wait, $clumpsOfSugar clumps of sugar!?") println("It is an unforgivable sin!!!") } } Control Flow - When Sample.kt
  • 93. val clumpsOfSugar = 0 when (clumpsOfSugar) { 0 -> println("The right way to drink coffee") 1, 2 -> println("It is a sin, but I can ignore") else -> { println("Wait, $clumpsOfSugar clumps of sugar!?") println("It is an unforgivable sin!!!") } } Control Flow - When Sample.kt
  • 94. val clumpsOfSugar = 0 when (clumpsOfSugar) { 0 -> println("The right way to drink coffee") 1, 2 -> println("It is a sin, but I can ignore") in 3..5 -> println("Is it a kind of candy???") else -> { println("Wait, $clumpsOfSugar clumps of sugar!?") println("It is an unforgivable sin!!!") } } Control Flow - When Sample.kt
  • 95. val clumpsOfSugar = 0 when (clumpsOfSugar) { 0 -> println("The right way to drink coffee") 1, 2 -> println("It is a sin, but I can ignore") !in 3..5 -> println("It is not 3, 4 or 5 :)") else -> { println("Wait, $clumpsOfSugar clumps of sugar!?") println("It is an unforgivable sin!!!") } } Control Flow - When Sample.kt
  • 96. val clumpsOfSugar = 0 val candyNumbers = arrayOf(3, 4, 5) when (clumpsOfSugar) { 0 -> println("The right way to drink coffee") 1, 2 -> println("It is a sin, but I can ignore") in candyNumbers -> println("Is it a kind of candy???") else -> { println("Wait, $clumpsOfSugar clumps of sugar!?") println("It is an unforgivable sin!!!") } } Control Flow - When Sample.kt
  • 97. val clumpsOfSugar = 0 when (clumpsOfSugar) { 0 -> println("The right way to drink coffee") 1, 2 -> println("It is a sin, but I can ignore") randomInt() -> println("Are we still talking about coffee?") else -> { println("Wait, $clumpsOfSugar clumps of sugar!?") println("It is an unforgivable sin!!!") } } Control Flow - When Sample.kt
  • 98. val clumpsOfSugar = 0 when { clumpsOfSugar % 2 == 1 -> println("An odd amount of sugar clumps") clumpsOfSugar % 2 == 0 -> println("An even amount of sugar clumps") else -> println("We have a really strange amount of sugar clumps") } Control Flow - When Sample.kt
  • 99. val clumpsOfSugar = 0 when { clumpsOfSugar.isOdd() -> println("An odd amount of sugar clumps") clumpsOfSugar.isEven() -> println("An even amount of sugar clumps") else -> println("We have a really strange amount of sugar clumps") } Control Flow - When Sample.kt
  • 101. var clumpsOfSugar = 10 while (clumpsOfSugar > 0) { clumpsOfSugar-- // yes we have -- and ++ syntax } println(clumpsOfSugar) // Prints 0 Control Flow - While Sample.kt
  • 102. var clumpsOfSugar = 10 do { clumpsOfSugar-- } while (clumpsOfSugar > 0) println(clumpsOfSugar) // Prints 0 Control Flow - While Sample.kt
  • 104. fun sayHelloWorld() { println("Hello World") } Function Sample.kt
  • 105. fun sayHelloWorld() = println("Hello World") Function Sample.kt
  • 106. fun say(message: String) { println(message) } Function Sample.kt
  • 107. fun say(message: String = "Hello World") { println(message) } Function Sample.kt
  • 108. fun sum(a: Int, b: Int): Int { return a + b } Function Sample.kt
  • 109. fun sum(a: Int, b: Int): Int = a + b Function Sample.kt
  • 110. fun sum(a: Int, b: Int) = a + b Function Sample.kt
  • 111. fun makeCoffee( milliliters: Int, concentration: Float, useSugar: Boolean = false) { // make your coffee } Function Sample.kt
  • 112. fun makeCoffee( milliliters: Int, concentration: Float, useSugar: Boolean = false) { // make your coffee } Function Sample.kt
  • 113. fun makeCoffee( milliliters: Int, concentration: Float, useSugar: Boolean = false) { // make your coffee } makeCoffee(200, 0.8f) Function Sample.kt
  • 114. fun makeCoffee( milliliters: Int, concentration: Float, useSugar: Boolean = false) { // make your coffee } makeCoffee(200, 0.8f, true) Function Sample.kt
  • 115. fun makeCoffee( milliliters: Int, concentration: Float, useSugar: Boolean = false) { // make your coffee } makeCoffee(200, 0.8f, useSugar = true) Function Sample.kt
  • 116. fun makeCoffee( milliliters: Int, concentration: Float, useSugar: Boolean = false) { // make your coffee } makeCoffee(milliliters = 200, concentration = 0.8f, useSugar = true) Function Sample.kt
  • 117. fun makeCoffee( milliliters: Int, concentration: Float, useSugar: Boolean = false) { // make your coffee } makeCoffee(useSugar = true, milliliters = 200, concentration = 0.8f) Function Sample.kt
  • 118. fun outside() { fun inside() { // Do something } // ... inside() // we can call in this scope // ... } Function Sample.kt
  • 119. Higher-Order Functions & Lambda Basics
  • 120. // Java on click listener setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // Do something } }); Higher-Order Functions & Lambda Sample.kt
  • 121. // Java 8 on click listener with lambda setOnClickListener(view -> { // Do something }); Higher-Order Functions & Lambda Sample.kt
  • 122. // Kotlin on click listener with lambda setOnClickListener { // Do something } Higher-Order Functions & Lambda Sample.kt
  • 123. fun sum(a: Int, b: Int, callback: (Int) -> Unit) { // Spoiler: Unit type val summed = a + b callback(summed) } Higher-Order Functions & Lambda Sample.kt
  • 124. fun sum(a: Int, b: Int, callback: (Int) -> Unit) { val summed = a + b callback(summed) } Higher-Order Functions & Lambda Sample.kt
  • 125. fun sum(a: Int, b: Int, callback: (Int) -> Unit) { val summed = a + b callback(summed) } sum(1, 2) { result -> println(result) // prints 3 } Higher-Order Functions & Lambda Sample.kt
  • 126. fun sum(a: Int, b: Int, callback: (Int) -> Unit) { val summed = a + b callback(summed) } sum(1, 2) { println(it) // Also prints 3 } Higher-Order Functions & Lambda Sample.kt
  • 127. val sum: (Int, Int) -> Int = { x: Int, y: Int -> x + y } Higher-Order Functions & Lambda Sample.kt
  • 128. val sum: (Int, Int) -> Int = { x: Int, y: Int -> x + y } Higher-Order Functions & Lambda Sample.kt
  • 129. val sum = { x: Int, y: Int -> x + y } Higher-Order Functions & Lambda Sample.kt
  • 130. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } Higher-Order Functions & Lambda Sample.kt
  • 131. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } Higher-Order Functions & Lambda Sample.kt
  • 132. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } Higher-Order Functions & Lambda Sample.kt
  • 133. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } Higher-Order Functions & Lambda Sample.kt
  • 134. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } calculation(3, 2, sum) Higher-Order Functions & Lambda Sample.kt
  • 135. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } calculation(3, 2, sum) // returns 5 Higher-Order Functions & Lambda Sample.kt
  • 136. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } calculation(3, 2, sum) calculation(3, 2, sub) Higher-Order Functions & Lambda Sample.kt
  • 137. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } calculation(3, 2, sum) calculation(3, 2, sub) // returns 1 Higher-Order Functions & Lambda Sample.kt
  • 138. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } calculation(3, 2, sum) calculation(3, 2, sub) Higher-Order Functions & Lambda Sample.kt
  • 139. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } calculation(3, 2, { x, y -> x * y }) Higher-Order Functions & Lambda Sample.kt
  • 140. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } calculation(3, 2, { x, y -> x * y }) // returns 6 Higher-Order Functions & Lambda Sample.kt
  • 141. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } calculation(3, 2) { x, y -> x * y } Higher-Order Functions & Lambda Sample.kt
  • 142. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } calculation(3, 2) { x, y -> x * y } Higher-Order Functions & Lambda Sample.kt
  • 143. val sum = { x: Int, y: Int -> x + y } val sub = { x: Int, y: Int -> x - y } fun calculation(a: Int, b: Int, rule: (Int, Int) -> Int): Int { return rule(a, b) } fun sum(a: Int, b: Int) = a + b calculation(3, 2, ::sum) Higher-Order Functions & Lambda Sample.kt
  • 144. OOP
  • 148. class Coffee val coffee = Coffee() Classes Coffee.kt
  • 151. class Coffee constructor(type: String) Constructor Coffee.kt
  • 152. class Coffee @Inject constructor(type: String) Constructor Coffee.kt
  • 153. class CustomView : View { // Spoiler: Inheritance constructor(c: Context) : super(c) {} constructor(c: Context, a: AttributeSet?) : super(c, a) {} constructor(c: Context, a: AttributeSet?, d: Int) : super(c, a, d) {} constructor(c: Context, a: AttributeSet?, d: Int, r: Int) : super(c, a, d, r) {} } Constructor CustomView.kt
  • 155. class Coffee(type: String) class Coffee(var type: String) Constructor Coffee.kt
  • 156. class Coffee(type: String) class Coffee(var type: String) class Coffee(val type: String) Constructor Coffee.kt
  • 157. class Coffee(type: String) class Coffee(var type: String) class Coffee(val type: String) class Coffee(private val type: String) Constructor Coffee.kt
  • 158. class Coffee(type: String) class Coffee(var type: String) class Coffee(val type: String) class Coffee(private val type: String) class Coffee(private val type: String = "Espresso") Constructor Coffee.kt
  • 159. class Coffee(type: String) { private val name = "Coffee $type" } Constructor Coffee.kt
  • 160. class Coffee(type: String) { private val name: String init { name = "Coffee $type" } } Constructor Coffee.kt
  • 161. class Coffee { private val name: String constructor(type: String) { name = "Coffee $type" } } Constructor Coffee.kt
  • 162. class Coffee(val type: String) { } Constructor Coffee.kt
  • 164. class Coffee { val type = "Espresso" var drinked = false private val gourmet = true } Properties Coffee.kt
  • 165. class Coffee { var type = "Espresso" get() { return field } set(value) { field = value } } Properties Coffee.kt
  • 166. class Coffee(context: Context) { private val preferences = context.getSharedPreferences("Coffee", MODE_PRIVATE) var type get() = preferences.getString("TypeKey", "Default") set(value) { preferences.edit().putString("TypeKey", value).apply() } } Properties Coffee.kt
  • 167. class Coffee { var type = "Espresso" private set } Properties Coffee.kt
  • 168. class Coffee { lateinit var type: String } Properties Coffee.kt
  • 169. class Coffee { @JsonField lateinit var type: String } Properties Coffee.kt
  • 170. class Coffee { val type: String by lazy { println("You are running this code!") "Hello" } val x = type val y = type } Properties Coffee.kt
  • 171. class Coffee { val type: String by lazy { println("You are running this code!") "Hello" } val x = type // It prints "You are running this code!" 1 time val y = type // It don't prints anything } Properties Coffee.kt
  • 173. Kotlin methods are functions, and you already know it.
  • 175. open class Coffee class Cappuccino : Coffee() Inheritance Coffee.kt
  • 176. open class Coffee(type: String) class Cappuccino : Coffee("Cappuccino") Inheritance Coffee.kt
  • 177. open class Coffee(type: String) class Cappuccino(type: String) : Coffee(type) Inheritance Coffee.kt
  • 178. open class Coffee { constructor(type: String) constructor(type: String, temperature: Float) } class Cappuccino : Coffee { constructor(type: String) : super(type) constructor(type: String, temperature: Float) : super(type, temperature) } Inheritance Coffee.kt
  • 179. open class Coffee { open fun drink() { println("So tasty") } } class Cappuccino : Coffee() { override fun drink() { super.drink() } } Inheritance Coffee.kt
  • 181. interface Drinkable class Coffee : Drinkable Interfaces Coffee.kt
  • 182. interface Drinkable { fun drink() } class Coffee : Drinkable { override fun drink() { println("So tasty") } } Interfaces Coffee.kt
  • 183. interface Drinkable { fun drink() { println("So tasty") } } class Coffee : Drinkable Interfaces Coffee.kt
  • 184. interface Drinkable { val type: String } class Coffee : Drinkable { override val type = "Coffee" } Interfaces Coffee.kt
  • 185. open class Coffee interface Drinkable { fun drink() } class Cappuccino : Coffee(), Drinkable { override fun drink() { println("So tasty") } } Interfaces Coffee.kt
  • 186. open class Coffee { open fun drink() = println("So coffee") } interface Drinkable { fun drink() = println("So tasty") } class Cappuccino : Coffee(), Drinkable { // What happens here ? } Interfaces Coffee.kt
  • 187. open class Coffee { open fun drink() = println("So coffee") } interface Drinkable { fun drink() = println("So tasty") } class Cappuccino : Coffee(), Drinkable { override fun drink() { super<Coffee>.drink() super<Drinkable>.drink() } } Interfaces Coffee.kt
  • 189. data class Coffee(val type: String) Data Classes Coffee.kt
  • 190. data class Coffee(val type: String) val a = Coffee("Cappuccino") val b = Coffee("Cappuccino") println(a == b) // Prints true Data Classes - Equals & HashCode Coffee.kt
  • 191. data class Coffee(val type: String) val a = Coffee("Cappuccino") val b = Coffee("Ristretto") println(a == b) // Prints false Data Classes - Equals & HashCode Coffee.kt
  • 192. data class Coffee(val type: String) val a = Coffee("Cappuccino") println(a.toString()) // Prints: Coffee(type=Cappuccino) Data Classes - toString() Coffee.kt
  • 193. data class Coffee(val type: String) val a = Coffee("Cappuccino") val b = a.copy() Data Classes - copy Coffee.kt
  • 194. data class Coffee(val type: String) val a = Coffee("Cappuccino") val b = a.copy() val c = a.copy(type = "Ristretto") Data Classes - copy Coffee.kt
  • 196. Any - Unit - Nothing Ad Libitum
  • 197. Any
  • 202. Any? Unit Any Coffee Coffee? String? Unit? Nothing? String
  • 203. Any? Unit Any Coffee Coffee? String? Unit? Nothing? Nothing String
  • 205. val message = "Hello World" message.let { println(it) } // prints: Hello World Let Sample.kt
  • 206. val message: String? = "Hello World" message?.let { println(it) } // prints: Hello World Let Sample.kt
  • 207. val message: String? = null message?.let { println(it) } // Don't print anything Let Sample.kt
  • 209. val textView = TextView(context) textView.layoutParams = LayoutParams(WRAP_CONTENT, WRAP_CONTENT) textView.textSize = context.resources.getDimension(R.dimen.text_size) textView.setTextColor(Color.RED) textView.text = "Hello World!" Apply Sample.kt
  • 210. val textView = TextView(context).apply { layoutParams = LayoutParams(WRAP_CONTENT, WRAP_CONTENT) textSize = context.resources.getDimension(R.dimen.text_size) setTextColor(Color.RED) text = "Hello World!" } Apply Sample.kt
  • 212. val textView = TextView(context) textView.layoutParams = LayoutParams(WRAP_CONTENT, WRAP_CONTENT) textView.textSize = context.resources.getDimension(R.dimen.text_size) textView.setTextColor(Color.RED) textView.text = "Hello World!" With Sample.kt
  • 213. val textView = TextView(context) with(textView) { layoutParams = LayoutParams(WRAP_CONTENT, WRAP_CONTENT) textSize = context.resources.getDimension(R.dimen.text_size) setTextColor(Color.RED) text = "Hello World!" } With Sample.kt
  • 215. listOf - mapOf - <type>ArrayOf Collections Ad Libitum
  • 216. val anEmptyList = listOf<String>() val anInferedTypeList = listOf("Hello", "World") val anIntegerList = listOf<Int>() val anotherInferedTypeList = listOf(1, 2, 3) Collections - listOf Sample.kt
  • 217. val aPrimitiveIntArray = intArrayOf(1, 2, 3) val aPrimitiveByteArray = byteArrayOf() val aPrimitiveBooleanArray = booleanArrayOf() Collections - <type>ArrayOf Sample.kt
  • 218. val aMap = mapOf<String, Boolean>() val aInferedMap = mapOf(Pair("Key-A", true), Pair("Key-B", false)) val aHashMap = hashMapOf<String, Int>() val alinkedMap = linkedMapOf<String, Any>() Collections - mapOf Sample.kt
  • 220. listOf(1, 2, 3, 4, 5) .forEach { item -> println(item) } // Prints 1, 2, 3, 4 and 5 Collections - Operators - Foreach Sample.kt
  • 221. listOf(1, 2, 3, 4, 5) .forEach { println(it) } // Prints 1, 2, 3, 4 and 5 Collections - Operators - Foreach Sample.kt
  • 222. listOf("Hello", "World") .forEachIndexed { index, item -> println("Item $item at index $index") } // Prints: Item Hello at index 0 and Item World at index 1 Collections - Operators - Filter Sample.kt
  • 223. listOf(1, 2, 3, 4, 5) .map { it * 2 } .forEach { println(it) } // Prints 2, 4, 6, 8 and 10 Collections - Operators - Map Sample.kt
  • 224. listOf(5, 3, 1, 4, 2) .sortedBy { it } .forEach { println(it) } // Prints 1, 2, 3, 4 and 5 Collections - Operators - Sort Sample.kt
  • 225. listOf(1, 2, 3, 4, 5) .filter { it > 2 } .forEach { print(it) } // Prints: 3, 4 and 5 Collections - Operators - Filter Sample.kt
  • 227. fun ViewGroup.inflate(layout: Int, attachToRoot: Boolean = true): View { val inflater = LayoutInflater.from(context) val view = inflater.inflate(layout, this, attachToRoot) return view } // Use it someViewGroup.inflate(R.layout.item) Extensions Sample.kt
  • 228. SLIDE 228 Now this is not the end. It is not even the beginning of the end. But it is, perhaps, the end of the beginning.