SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
Let’s fly to the Kotlin
island
short and comprehensive introduction
Aliaksei Zhynhiarouski
1
http://try.kotl.in
2
Kotlin Island
3
Why is Kotlin
• Static Typing
• Java + Kotlin = ❤. 

Effortless mixing both in one project
• Java Interoperability. 

100% interoperable with Java.
4
Why is Kotlin
• Null Safety
• Type Inference
• Immutability in the mind
• fun
5
fun main(args : Array<String>) {
println("Hello, MO 2016!")
}
6
val from_value : Type
var from_variable : Type
val i_am_string = “mobile”
var i_am_long = 666L
val i_am_double = 3.14e10
7
val & var
Null Safety
// can’t be null

val foo: String = “mobile”


// need always perform the check 

val bar: String? = null
8
Type? = Type or null
Null Safety
val bar: String? = “mobile”


var a = bar?.length // 6



var b = bar?.length?.inc() // 7



var c = bar!!.length // can be NPE
9
Null Safety
val bar: String? = null


var a = if (bar != null) bar.length

else 0 // 0



var b = bar?.length ?: 0 // 0

10
Type Definition
class Phone(val brand: String)
11
• concise syntax for constructor
• properties – not fields
• final by default. Use open to open
• simple old java class under the hood
Type Definition
class Phone(val brand: String){
var version: Int = 0
}
12
get() {…}

private set
val phone = Phone(“Apple”)

phone.brand == “Apple” // true
Value Object
data class Phone(val brand: String)
13
Lombok – no more
Get ready to be inspired
14
Delegates
15
class Foo<T> : List<T> {
private val innerList = arrayListOf<T>()
override val size: Int get() = innerList.size
override fun isEmpty() = innerList.isEmpty()
…

…
…
}
Delegates – right way
16
class Foo<T>
( innerList : List<T> = ArrayList<T>() )
: List<T> by innerList
All functions invocation delegated to innerList
Delegates – right way
17
class View {















}
val lazyProp by lazy { “mobile” }
val ops by observable(“”) { 

prop, old, new ->
print("$old to $new")
}
Delegates – wow way
18
class Activity {













}
private val btn: Button by lazy {

findViewById(R.id.btn) as Button

}



override fun onCreate(savedBundle: Bundle?) {

btn.setText(“Optimize!”)

}


Delegates – wow way
19
class SMS(val props: Map<String, String>) {



}
val date by props

val address by props



val info: String

get() {

“$date - $address” 

}
Delegates – wow way
20
class SMS(val props: Map<String, String>) {



}
val date by props

val address by props

…

val props = mapOf(“date” to “128932”,

“address” to “Sweden”)

val sms = SMS(props)
print(sms.info) // “128932 - Sweden”

Get ready to be inspired
21
Extensions
22
// Example



“Mobile”.lastChar() // “e”

// Definition



fun String.lastChar():Char 

= this.get(length - 1)
Extensions
23
// Java under the hood



@file:JvmName(“StringUtils")

StringUtils.lastChar(“Mobile”);
Extensions
24
Collections.max(list)



↓
list.max()
Extensions
25
operator fun BigDecimal.inc() 

= this + BigDecimal.ONE


// Example

var counter = BigDecimal.ZERO



print(++counter) // 1
Fun
26
Named Parameters
// Bad

ContentResolver.query(URI, new String[]{ },

null, null, null);
// Good

ContentResolver.query(URI, 

projection = new String[]{ },

selection = null,

selectionArgs = null,

sortOrder = null)
Fun
27
Named Parameters & Default Values
// Bad

IN_PROGRESS(true, false, false, false, false, false),

FAILED (false, true, true, false, false, false),

COMPLETE (true, false, true, false, false, true)



// Good

COMPLETE(stop = true, 

cancel = true, 

disable = true)

Fun
28
Named Parameters & Default Values
// Awesome



class COMPLETE(

stop: Boolean = false,

cancel: Boolean = false,

…

…)
Lambdas
29
val boys = listOf(

Boy(“Alex”), Boy(“Magnus”), Boy(“Nils”))

// 1 

boys.filter({ b: Boy -> b.age > 18 })

// 2

boys.filter({ it.age > 18 })


// 3

boys.filter { it.age > 18 }
λ
30
boys.filter { it.age > 18 }
.map { Pair(it, Boy("Eugene")) }
.forEach { dance(it) }
// Under the hood



inline fun <T> Iterable<T>.filter

(predicate: (T) -> Boolean)

DSL
31
• Type-safe
• Express your code by flexible syntax
• Ideal to build own query engine
• if/for/when just inside DSL
DSL
32
"(#C1 = :active) AND (#C2 = :type) AND " +
"(attribute_not_exists(#C1) OR #C1 IN
(:model, :allModels)) AND " +

"...";

if (smth)

append("(#C2 = :active) AND NOT
contains(#C3, :brandAll)");
…
// wait, oh shi~
DSL
33
val expr = filterExpr {

group {

eq("#1", ":2") and eq("#1", ":2") 

or group {

eq("#2", ":2")

if (smth) { 

and eq("#2", ":2") 

}

}

and ……

}
One more DSL thing
34
Gradle meets Kotlin
Kotlin 1.1
• Direct Java 8/9 support
• Type aliases
• Delegated properties everywhere
• Coroutines with async/await
35
bit.ly/kotlin_11
Kotlin 1.1
typealias Callback<T> = (T) -> T
// And now

fun alias(cb: Callback<String>) {}
36
Type aliases
Kotlin 1.1
typealias Table<K> = 

MutableMap<K,MutableList<String>>
37
Type aliases
Kotlin 1.1
fun (cb: Callback<String>) {



val callonce by lazy { cb("MO 2016") }
println(callonce)
}
38
Local delegated properties
Kotlin 1.1
val future = async<String> {
(1..5).map {
await(loooongAsyncOperation(it))



}.joinToString("n")
}
39
Coroutines with async/await
Kotlin friends
40
jprof.by
Belarus Kotlin User Group
bkug.by
Links
Awesome Kotlin kotlin.link
Slack kotlinlang.slack.com 

Local Chat gitter.im/JavaBy/Kotlin

41
Start your journey
with
42
twitter: @a_lithium

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Sway Wang
 

Was ist angesagt? (20)

Kotlin Backstage
Kotlin BackstageKotlin Backstage
Kotlin Backstage
 
C++ Programming - 5th Study
C++ Programming - 5th StudyC++ Programming - 5th Study
C++ Programming - 5th Study
 
The Lesser Known Features of ECMAScript 6
The Lesser Known Features of ECMAScript 6The Lesser Known Features of ECMAScript 6
The Lesser Known Features of ECMAScript 6
 
Kotlin for Android Developers
Kotlin for Android DevelopersKotlin for Android Developers
Kotlin for Android Developers
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
 
Exploring slides
Exploring slidesExploring slides
Exploring slides
 
dplyr
dplyrdplyr
dplyr
 
Functional Pe(a)rls version 2
Functional Pe(a)rls version 2Functional Pe(a)rls version 2
Functional Pe(a)rls version 2
 
A practical introduction to Kotlin
A practical introduction to KotlinA practical introduction to Kotlin
A practical introduction to Kotlin
 
Kotlin Collections
Kotlin CollectionsKotlin Collections
Kotlin Collections
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Продвинутая отладка JavaScript с помощью Chrome Dev Tools
Продвинутая отладка JavaScript с помощью Chrome Dev ToolsПродвинутая отладка JavaScript с помощью Chrome Dev Tools
Продвинутая отладка JavaScript с помощью Chrome Dev Tools
 
Introduzione a C#
Introduzione a C#Introduzione a C#
Introduzione a C#
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Grokking TechTalk #16: Maybe functor in javascript
Grokking TechTalk #16: Maybe functor in javascriptGrokking TechTalk #16: Maybe functor in javascript
Grokking TechTalk #16: Maybe functor in javascript
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using Scala
 
Fractal proj report 2
Fractal proj report 2Fractal proj report 2
Fractal proj report 2
 
Git avançado
Git avançadoGit avançado
Git avançado
 
Effective ES6
Effective ES6Effective ES6
Effective ES6
 
TDC2017 | São Paulo - Trilha Android How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Android How we figured out we had a SRE team at ...TDC2017 | São Paulo - Trilha Android How we figured out we had a SRE team at ...
TDC2017 | São Paulo - Trilha Android How we figured out we had a SRE team at ...
 

Andere mochten auch

Andere mochten auch (13)

「RAD Studioアプリケーションとバックエンドシステムを接続する」
「RAD Studioアプリケーションとバックエンドシステムを接続する」「RAD Studioアプリケーションとバックエンドシステムを接続する」
「RAD Studioアプリケーションとバックエンドシステムを接続する」
 
Clasificacion de los triangulos
Clasificacion de los triangulosClasificacion de los triangulos
Clasificacion de los triangulos
 
Preparing your B2B Site for Marketing Automation
Preparing your B2B Site for Marketing AutomationPreparing your B2B Site for Marketing Automation
Preparing your B2B Site for Marketing Automation
 
Fitxes Mercè per Alumnat Nouvingut.
Fitxes Mercè per Alumnat Nouvingut.Fitxes Mercè per Alumnat Nouvingut.
Fitxes Mercè per Alumnat Nouvingut.
 
「RAD Studio 10.1 Berlinで始めるIoTアプリケーション構築」
「RAD Studio 10.1 Berlinで始めるIoTアプリケーション構築」「RAD Studio 10.1 Berlinで始めるIoTアプリケーション構築」
「RAD Studio 10.1 Berlinで始めるIoTアプリケーション構築」
 
ShirleyZabalaMapaConceptual
ShirleyZabalaMapaConceptualShirleyZabalaMapaConceptual
ShirleyZabalaMapaConceptual
 
Acondroplasia. atención primaria.
Acondroplasia. atención primaria.Acondroplasia. atención primaria.
Acondroplasia. atención primaria.
 
Discapacidad intelectual y bienestar social.
Discapacidad intelectual y bienestar social.Discapacidad intelectual y bienestar social.
Discapacidad intelectual y bienestar social.
 
Mandalas para la paz
Mandalas para la pazMandalas para la paz
Mandalas para la paz
 
Los aceleradores de partíuclas y el lhc
Los aceleradores de partíuclas y el lhcLos aceleradores de partíuclas y el lhc
Los aceleradores de partíuclas y el lhc
 
Ortho discuss-spine fx
Ortho discuss-spine fxOrtho discuss-spine fx
Ortho discuss-spine fx
 
ATS-Catalogue-Latest
ATS-Catalogue-LatestATS-Catalogue-Latest
ATS-Catalogue-Latest
 
Creative Mornings San Diego 2016
Creative Mornings San Diego 2016Creative Mornings San Diego 2016
Creative Mornings San Diego 2016
 

Ähnlich wie Let's fly to the Kotlin Island. Just an introduction to Kotlin

Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
Andrey Breslav
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 

Ähnlich wie Let's fly to the Kotlin Island. Just an introduction to Kotlin (20)

Kotlin
KotlinKotlin
Kotlin
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Criando app Android utilizando Kotlin
Criando app Android utilizando KotlinCriando app Android utilizando Kotlin
Criando app Android utilizando Kotlin
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
 
Exploring Koltin on Android
Exploring Koltin on AndroidExploring Koltin on Android
Exploring Koltin on Android
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
 
Kotlin Starter Pack
Kotlin Starter PackKotlin Starter Pack
Kotlin Starter Pack
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 
Bologna Developer Zone - About Kotlin
Bologna Developer Zone - About KotlinBologna Developer Zone - About Kotlin
Bologna Developer Zone - About Kotlin
 
XKE Typeclass
XKE TypeclassXKE Typeclass
XKE Typeclass
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 

Kürzlich hochgeladen

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Kürzlich hochgeladen (20)

WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

Let's fly to the Kotlin Island. Just an introduction to Kotlin

  • 1. Let’s fly to the Kotlin island short and comprehensive introduction Aliaksei Zhynhiarouski 1
  • 4. Why is Kotlin • Static Typing • Java + Kotlin = ❤. 
 Effortless mixing both in one project • Java Interoperability. 
 100% interoperable with Java. 4
  • 5. Why is Kotlin • Null Safety • Type Inference • Immutability in the mind • fun 5
  • 6. fun main(args : Array<String>) { println("Hello, MO 2016!") } 6
  • 7. val from_value : Type var from_variable : Type val i_am_string = “mobile” var i_am_long = 666L val i_am_double = 3.14e10 7 val & var
  • 8. Null Safety // can’t be null
 val foo: String = “mobile” 
 // need always perform the check 
 val bar: String? = null 8 Type? = Type or null
  • 9. Null Safety val bar: String? = “mobile” 
 var a = bar?.length // 6
 
 var b = bar?.length?.inc() // 7
 
 var c = bar!!.length // can be NPE 9
  • 10. Null Safety val bar: String? = null 
 var a = if (bar != null) bar.length
 else 0 // 0
 
 var b = bar?.length ?: 0 // 0
 10
  • 11. Type Definition class Phone(val brand: String) 11 • concise syntax for constructor • properties – not fields • final by default. Use open to open • simple old java class under the hood
  • 12. Type Definition class Phone(val brand: String){ var version: Int = 0 } 12 get() {…}
 private set val phone = Phone(“Apple”)
 phone.brand == “Apple” // true
  • 13. Value Object data class Phone(val brand: String) 13 Lombok – no more
  • 14. Get ready to be inspired 14
  • 15. Delegates 15 class Foo<T> : List<T> { private val innerList = arrayListOf<T>() override val size: Int get() = innerList.size override fun isEmpty() = innerList.isEmpty() …
 … … }
  • 16. Delegates – right way 16 class Foo<T> ( innerList : List<T> = ArrayList<T>() ) : List<T> by innerList All functions invocation delegated to innerList
  • 17. Delegates – right way 17 class View {
 
 
 
 
 
 
 
 } val lazyProp by lazy { “mobile” } val ops by observable(“”) { 
 prop, old, new -> print("$old to $new") }
  • 18. Delegates – wow way 18 class Activity {
 
 
 
 
 
 
 } private val btn: Button by lazy {
 findViewById(R.id.btn) as Button
 }
 
 override fun onCreate(savedBundle: Bundle?) {
 btn.setText(“Optimize!”)
 } 

  • 19. Delegates – wow way 19 class SMS(val props: Map<String, String>) {
 
 } val date by props
 val address by props
 
 val info: String
 get() {
 “$date - $address” 
 }
  • 20. Delegates – wow way 20 class SMS(val props: Map<String, String>) {
 
 } val date by props
 val address by props
 …
 val props = mapOf(“date” to “128932”,
 “address” to “Sweden”)
 val sms = SMS(props) print(sms.info) // “128932 - Sweden”

  • 21. Get ready to be inspired 21
  • 22. Extensions 22 // Example
 
 “Mobile”.lastChar() // “e”
 // Definition
 
 fun String.lastChar():Char 
 = this.get(length - 1)
  • 23. Extensions 23 // Java under the hood
 
 @file:JvmName(“StringUtils")
 StringUtils.lastChar(“Mobile”);
  • 25. Extensions 25 operator fun BigDecimal.inc() 
 = this + BigDecimal.ONE 
 // Example
 var counter = BigDecimal.ZERO
 
 print(++counter) // 1
  • 26. Fun 26 Named Parameters // Bad
 ContentResolver.query(URI, new String[]{ },
 null, null, null); // Good
 ContentResolver.query(URI, 
 projection = new String[]{ },
 selection = null,
 selectionArgs = null,
 sortOrder = null)
  • 27. Fun 27 Named Parameters & Default Values // Bad
 IN_PROGRESS(true, false, false, false, false, false),
 FAILED (false, true, true, false, false, false),
 COMPLETE (true, false, true, false, false, true)
 
 // Good
 COMPLETE(stop = true, 
 cancel = true, 
 disable = true)

  • 28. Fun 28 Named Parameters & Default Values // Awesome
 
 class COMPLETE(
 stop: Boolean = false,
 cancel: Boolean = false,
 …
 …)
  • 29. Lambdas 29 val boys = listOf(
 Boy(“Alex”), Boy(“Magnus”), Boy(“Nils”))
 // 1 
 boys.filter({ b: Boy -> b.age > 18 })
 // 2
 boys.filter({ it.age > 18 }) 
 // 3
 boys.filter { it.age > 18 }
  • 30. λ 30 boys.filter { it.age > 18 } .map { Pair(it, Boy("Eugene")) } .forEach { dance(it) } // Under the hood
 
 inline fun <T> Iterable<T>.filter
 (predicate: (T) -> Boolean)

  • 31. DSL 31 • Type-safe • Express your code by flexible syntax • Ideal to build own query engine • if/for/when just inside DSL
  • 32. DSL 32 "(#C1 = :active) AND (#C2 = :type) AND " + "(attribute_not_exists(#C1) OR #C1 IN (:model, :allModels)) AND " +
 "...";
 if (smth)
 append("(#C2 = :active) AND NOT contains(#C3, :brandAll)"); … // wait, oh shi~
  • 33. DSL 33 val expr = filterExpr {
 group {
 eq("#1", ":2") and eq("#1", ":2") 
 or group {
 eq("#2", ":2")
 if (smth) { 
 and eq("#2", ":2") 
 }
 }
 and ……
 }
  • 34. One more DSL thing 34 Gradle meets Kotlin
  • 35. Kotlin 1.1 • Direct Java 8/9 support • Type aliases • Delegated properties everywhere • Coroutines with async/await 35 bit.ly/kotlin_11
  • 36. Kotlin 1.1 typealias Callback<T> = (T) -> T // And now
 fun alias(cb: Callback<String>) {} 36 Type aliases
  • 37. Kotlin 1.1 typealias Table<K> = 
 MutableMap<K,MutableList<String>> 37 Type aliases
  • 38. Kotlin 1.1 fun (cb: Callback<String>) {
 
 val callonce by lazy { cb("MO 2016") } println(callonce) } 38 Local delegated properties
  • 39. Kotlin 1.1 val future = async<String> { (1..5).map { await(loooongAsyncOperation(it))
 
 }.joinToString("n") } 39 Coroutines with async/await