SlideShare a Scribd company logo
Kotlin in Action
A concise way to code Android Projects
in a smarter way
© 2016
What is Kotlin?
...it’s just another language…
● Created by Jetbrains
● Statically typed
● Lightweight
● Running on JVM
Old fashion Android Coding
● Android supports only Java6(ish)
● The verbosity of Java is annoying (i.e. a lot of boilerplate code)
● The Billion Dollar Mistake (aka Null Reference)
Why Kotlin?
● Concise: Reduce the boilerplate code, no ceremonies, no decorations
● Safe: It’s a Null Safety language
● Versatile: Write Android, Front end and Server Side applications
● Interoperable: Write Kotlin and Java code in the same project
Kotlin Language
The Language
fun getAvg(a: Int, b: Int): Int {
return (a + b) / 2
}
fun getAvg(a: Int, b: Int) = (a + b) / 2
val number: Int = 0
val stringArray = ArrayList<String>()
var average: Float? = null
Extension Functions
Simply way to extend a class adding new functions
fun Context.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, message, duration).show()
}
…
toast("Hello Folks!")
Extension Functions
fun MutableList<Int>.swap(index1: Int, index2: Int) {
val tmp = this[index1] // 'this' corresponds to the list
this[index1] = this[index2]
this[index2] = tmp
}
fun <T> MutableList<T>.swap(index1: Int, index2: Int) {
val tmp = this[index1] // 'this' corresponds to the list
this[index1] = this[index2]
this[index2] = tmp
}
Extension Functions
fun ImageView.loadImage(url: String) {
Glide.with(context)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.fitCenter()
.into(this)
}
Lambda Expression Syntax
val sum : (Int, Int) -> Int = {x: Int, y: Int -> x + y}
val sum = { x: Int, y: Int -> x + y }
val notEmpty: (String) -> Boolean = { !it.isEmpty() }
val notEmpty = { it: String -> !it.isEmpty() }
Higher-Order Functions and Lambdas
A function that takes functions as parameters, or returns a function
fun getId(id: Int, func: (Int) -> String): String {
return func(id)
}
val hereMyID = getId(101478, { x -> "Here My Id: $x" })
Lazy Initialization
var mySdk : Sdk? = null
mySdk = Sdk()
Sdk mySdk = null;
mySdk = new Sdk();
Java Kotlin
lateinit var mySdk : Sdk
mySdk = Sdk()
Lazy Initialization
Kotlin
class JavaClass {
Sdk mySdk;
final Sdk getSdk() {
if (mySdk == null) {
mySdk = new Sdk();
}
return mySdk;
}
}
val mySdk : Sdk by lazy { getSdk() }
protected fun getSdk() = Sdk()
Java
val mySdk : Sdk by lazy { Sdk() }
Kotlin Android Extensions Library
Java:
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
Kotlin:
recyclerView = findViewById(R.id.recycler_view) as RecyclerView
Kotter Knife:
val recyclerView by bindView<RecyclerView>(R.id.recycler_view)
Extensions Library: just import
import kotlinx.android.synthetic.main.my_layout.*
Android Extensions Library
Pros:
● Compile time check
● No casts
● Less error prone.
● No libraries in your build.gradle (less methods!) (Butterknife is 342)
● Can import Views from different flavors
Anko
Anko is a DSL (Domain-specific language) written in Kotlin to simplify the
programmatically creation of UI.
Much more:
● Intents
● Fragments
● Services
● Configuration qualifiers
● Dialogs and toasts
● Asynchronous tasks
● Logging
● Using SQLite
● Extending Anko
val intent = Intent(this, javaClass<SomeActivity>())
intent.putExtra("id", 5)
intent.putExtra("name", "John")
startActivity(intent)
startActivity(Intent(this, SomeActivity::class.java).
putExtra("id", 5).putExtra("name", "John"))
startActivity<SomeActivity>("id" to 5, "name" to "John")
Anko - Intents
Kotlin i.e. 1
Kotlin i.e. 2
Kotlin with Anko
async {
// Long background task
uiThread {
result.text = "Done"
}
}
val executor = Executors.newScheduledThreadPool(4)
async(executor) {
// Some task
}
Anko - AsyncTask
class SomeActivity : Activity(), AnkoLogger {
private fun someMethod() {
info("London is the capital of Great Britain")
debug(5) // .toString() method will be executed
warn(null) // "null" will be printed
wtf(“Oh, No!”)
}
}
Anko - Logger
Kotlin Configuration
Configuration
● JDK7
● Android Studio
Preferences -> Plugin - > Install JetBrain Plugins -> Kotlin
Configuration
Create a New Project
Tools -> Kotlin -> Configure Kotlin in Project
build.gradle (Module :app)
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
…
…
…
}
Kotlin by Examples
API: http://thecatapi.com
Endpoint: /api/images/get?format=xml&results_per_page=10
The Amazing Android App for Funny Cats
<response>
<data>
<images>
<image>
<url>
http://24.media.tumblr.com/tumblr_llees8B3V31qbe5pxo1_500.jpg
</url>
<id>9j6</id>
<source_url>http://thecatapi.com/?id=9j6</source_url>
</image>
<image>
<url>
http://25.media.tumblr.com/tumblr_m4g9rvBP441qz6jrko1_400.jpg
</url>
<id>a1k</id>
<source_url>http://thecatapi.com/?id=a1k</source_url>
</image>
</images>
</data>
</response>
Ciro Rizzo Enzo Belli
Senior Application Developer @QVC Senior Android Developer @YoYoWallet
@JackRix
http://www.cirorizzo.net/
@enzobelli
© 2016
https://kotlinlang.org/
https://github.com/cirorizzo/KShows
https://github.com/cirorizzo/JShows

More Related Content

PDF
ADG Poznań - Kotlin for Android developers
PDF
Kotlin Developer Starter in Android projects
PDF
Kotlin hands on - MorningTech ekito 2017
PDF
Kotlin advanced - language reference for android developers
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
PDF
The Kotlin Programming Language, Svetlana Isakova
PDF
Kotlin, smarter development for the jvm
PDF
Kotlin cheat sheet by ekito
ADG Poznań - Kotlin for Android developers
Kotlin Developer Starter in Android projects
Kotlin hands on - MorningTech ekito 2017
Kotlin advanced - language reference for android developers
Develop your next app with kotlin @ AndroidMakersFr 2017
The Kotlin Programming Language, Svetlana Isakova
Kotlin, smarter development for the jvm
Kotlin cheat sheet by ekito

What's hot (18)

PDF
Swift and Kotlin Presentation
PDF
Kotlin for Android - Vali Iorgu - mRready
PDF
Taking Kotlin to production, Seriously
PDF
Little Helpers for Android Development with Kotlin
PDF
Introduction to kotlin
PDF
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
PDF
Kotlin - Better Java
PDF
Kotlin boost yourproductivity
PPTX
Introduction to kotlin + spring boot demo
PDF
Kotlin: Why Do You Care?
PPTX
PPT
The Kotlin Programming Language
PDF
Coding for Android on steroids with Kotlin
PDF
scala.reflect, Eugene Burmako
PDF
Kotlin for Android devs
PDF
Kotlin Slides from Devoxx 2011
PDF
Kotlin Bytecode Generation and Runtime Performance
PDF
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
Swift and Kotlin Presentation
Kotlin for Android - Vali Iorgu - mRready
Taking Kotlin to production, Seriously
Little Helpers for Android Development with Kotlin
Introduction to kotlin
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Kotlin - Better Java
Kotlin boost yourproductivity
Introduction to kotlin + spring boot demo
Kotlin: Why Do You Care?
The Kotlin Programming Language
Coding for Android on steroids with Kotlin
scala.reflect, Eugene Burmako
Kotlin for Android devs
Kotlin Slides from Devoxx 2011
Kotlin Bytecode Generation and Runtime Performance
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
Ad

Viewers also liked (20)

PDF
A brief introduction to Realm with Kotlin
PDF
No excuses, switch to kotlin
PDF
Светлана Исакова «Язык Kotlin»
PDF
Kotlin Advanced - language reference for Android developers
PPTX
Android & Kotlin - The code awakens #03
PPTX
Android & Kotlin - The code awakens #01
PPT
Smoothing Your Java with DSLs
PPTX
Exploring Anko Components, Kotlin, Android
PDF
Дмитрий Юницкий. «Android NDK или как я перестал бояться и полюбил нативную р...
PDF
The Shape of Functional Programming
ODP
Introduction to Zeder - a production rules toolkit for Clojure
PDF
The Macronomicon
KEY
ClojureScript Anatomy
PDF
Getting started-kotlin-android
PDF
Fertile Ground: The Roots of Clojure
PPT
いまさら聞けないRake入門
KEY
The Return of the Living Datalog
PPTX
Android Workshop
PPTX
SeaJUG May 2012 mybatis
PPTX
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
A brief introduction to Realm with Kotlin
No excuses, switch to kotlin
Светлана Исакова «Язык Kotlin»
Kotlin Advanced - language reference for Android developers
Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #01
Smoothing Your Java with DSLs
Exploring Anko Components, Kotlin, Android
Дмитрий Юницкий. «Android NDK или как я перестал бояться и полюбил нативную р...
The Shape of Functional Programming
Introduction to Zeder - a production rules toolkit for Clojure
The Macronomicon
ClojureScript Anatomy
Getting started-kotlin-android
Fertile Ground: The Roots of Clojure
いまさら聞けないRake入門
The Return of the Living Datalog
Android Workshop
SeaJUG May 2012 mybatis
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
Ad

Similar to Kotlin in action (20)

PDF
Save time with kotlin in android development
PDF
Practical tips for building apps with kotlin
PPTX
Nice to meet Kotlin
PPTX
Kotlin – the future of android
PDF
Kotlin for Android Development
PPTX
Exploring Kotlin language basics for Android App development
PDF
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
PPTX
Fall in love with Kotlin
PDF
Kotlin for Android Developers
PPTX
Kotlin for android 2019
PPTX
Introduction to Kotlin Language and its application to Android platform
PDF
A quick and fast intro to Kotlin
PDF
Having Fun with Kotlin Android - DILo Surabaya
PPTX
Intro to kotlin 2018
PDF
Kotlin a problem solver - gdd extended pune
PDF
Lightning talk: Kotlin
PDF
Why Kotlin is your next language?
PPTX
Introduction to kotlin
PPTX
Geecon - Improve your Android-fu with Kotlin
PDF
Anko - The Ultimate Ninja of Kotlin Libraries?
Save time with kotlin in android development
Practical tips for building apps with kotlin
Nice to meet Kotlin
Kotlin – the future of android
Kotlin for Android Development
Exploring Kotlin language basics for Android App development
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Fall in love with Kotlin
Kotlin for Android Developers
Kotlin for android 2019
Introduction to Kotlin Language and its application to Android platform
A quick and fast intro to Kotlin
Having Fun with Kotlin Android - DILo Surabaya
Intro to kotlin 2018
Kotlin a problem solver - gdd extended pune
Lightning talk: Kotlin
Why Kotlin is your next language?
Introduction to kotlin
Geecon - Improve your Android-fu with Kotlin
Anko - The Ultimate Ninja of Kotlin Libraries?

Recently uploaded (20)

PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
AI in Product Development-omnex systems
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Digital Strategies for Manufacturing Companies
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
L1 - Introduction to python Backend.pptx
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
System and Network Administration Chapter 2
Operating system designcfffgfgggggggvggggggggg
AI in Product Development-omnex systems
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Which alternative to Crystal Reports is best for small or large businesses.pdf
CHAPTER 2 - PM Management and IT Context
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Digital Strategies for Manufacturing Companies
How to Migrate SBCGlobal Email to Yahoo Easily
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
wealthsignaloriginal-com-DS-text-... (1).pdf
L1 - Introduction to python Backend.pptx
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
How Creative Agencies Leverage Project Management Software.pdf
Odoo Companies in India – Driving Business Transformation.pdf
ai tools demonstartion for schools and inter college
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
System and Network Administration Chapter 2

Kotlin in action

  • 1. Kotlin in Action A concise way to code Android Projects in a smarter way © 2016
  • 2. What is Kotlin? ...it’s just another language… ● Created by Jetbrains ● Statically typed ● Lightweight ● Running on JVM
  • 3. Old fashion Android Coding ● Android supports only Java6(ish) ● The verbosity of Java is annoying (i.e. a lot of boilerplate code) ● The Billion Dollar Mistake (aka Null Reference)
  • 4. Why Kotlin? ● Concise: Reduce the boilerplate code, no ceremonies, no decorations ● Safe: It’s a Null Safety language ● Versatile: Write Android, Front end and Server Side applications ● Interoperable: Write Kotlin and Java code in the same project
  • 6. The Language fun getAvg(a: Int, b: Int): Int { return (a + b) / 2 } fun getAvg(a: Int, b: Int) = (a + b) / 2 val number: Int = 0 val stringArray = ArrayList<String>() var average: Float? = null
  • 7. Extension Functions Simply way to extend a class adding new functions fun Context.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, message, duration).show() } … toast("Hello Folks!")
  • 8. Extension Functions fun MutableList<Int>.swap(index1: Int, index2: Int) { val tmp = this[index1] // 'this' corresponds to the list this[index1] = this[index2] this[index2] = tmp } fun <T> MutableList<T>.swap(index1: Int, index2: Int) { val tmp = this[index1] // 'this' corresponds to the list this[index1] = this[index2] this[index2] = tmp }
  • 9. Extension Functions fun ImageView.loadImage(url: String) { Glide.with(context) .load(url) .diskCacheStrategy(DiskCacheStrategy.ALL) .fitCenter() .into(this) }
  • 10. Lambda Expression Syntax val sum : (Int, Int) -> Int = {x: Int, y: Int -> x + y} val sum = { x: Int, y: Int -> x + y } val notEmpty: (String) -> Boolean = { !it.isEmpty() } val notEmpty = { it: String -> !it.isEmpty() }
  • 11. Higher-Order Functions and Lambdas A function that takes functions as parameters, or returns a function fun getId(id: Int, func: (Int) -> String): String { return func(id) } val hereMyID = getId(101478, { x -> "Here My Id: $x" })
  • 12. Lazy Initialization var mySdk : Sdk? = null mySdk = Sdk() Sdk mySdk = null; mySdk = new Sdk(); Java Kotlin lateinit var mySdk : Sdk mySdk = Sdk()
  • 13. Lazy Initialization Kotlin class JavaClass { Sdk mySdk; final Sdk getSdk() { if (mySdk == null) { mySdk = new Sdk(); } return mySdk; } } val mySdk : Sdk by lazy { getSdk() } protected fun getSdk() = Sdk() Java val mySdk : Sdk by lazy { Sdk() }
  • 14. Kotlin Android Extensions Library Java: recyclerView = (RecyclerView)findViewById(R.id.recycler_view); Kotlin: recyclerView = findViewById(R.id.recycler_view) as RecyclerView Kotter Knife: val recyclerView by bindView<RecyclerView>(R.id.recycler_view) Extensions Library: just import import kotlinx.android.synthetic.main.my_layout.*
  • 15. Android Extensions Library Pros: ● Compile time check ● No casts ● Less error prone. ● No libraries in your build.gradle (less methods!) (Butterknife is 342) ● Can import Views from different flavors
  • 16. Anko Anko is a DSL (Domain-specific language) written in Kotlin to simplify the programmatically creation of UI. Much more: ● Intents ● Fragments ● Services ● Configuration qualifiers ● Dialogs and toasts ● Asynchronous tasks ● Logging ● Using SQLite ● Extending Anko
  • 17. val intent = Intent(this, javaClass<SomeActivity>()) intent.putExtra("id", 5) intent.putExtra("name", "John") startActivity(intent) startActivity(Intent(this, SomeActivity::class.java). putExtra("id", 5).putExtra("name", "John")) startActivity<SomeActivity>("id" to 5, "name" to "John") Anko - Intents Kotlin i.e. 1 Kotlin i.e. 2 Kotlin with Anko
  • 18. async { // Long background task uiThread { result.text = "Done" } } val executor = Executors.newScheduledThreadPool(4) async(executor) { // Some task } Anko - AsyncTask
  • 19. class SomeActivity : Activity(), AnkoLogger { private fun someMethod() { info("London is the capital of Great Britain") debug(5) // .toString() method will be executed warn(null) // "null" will be printed wtf(“Oh, No!”) } } Anko - Logger
  • 21. Configuration ● JDK7 ● Android Studio Preferences -> Plugin - > Install JetBrain Plugins -> Kotlin
  • 22. Configuration Create a New Project Tools -> Kotlin -> Configure Kotlin in Project
  • 23. build.gradle (Module :app) buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { … … … }
  • 25. API: http://thecatapi.com Endpoint: /api/images/get?format=xml&results_per_page=10 The Amazing Android App for Funny Cats <response> <data> <images> <image> <url> http://24.media.tumblr.com/tumblr_llees8B3V31qbe5pxo1_500.jpg </url> <id>9j6</id> <source_url>http://thecatapi.com/?id=9j6</source_url> </image> <image> <url> http://25.media.tumblr.com/tumblr_m4g9rvBP441qz6jrko1_400.jpg </url> <id>a1k</id> <source_url>http://thecatapi.com/?id=a1k</source_url> </image> </images> </data> </response>
  • 26. Ciro Rizzo Enzo Belli Senior Application Developer @QVC Senior Android Developer @YoYoWallet @JackRix http://www.cirorizzo.net/ @enzobelli © 2016 https://kotlinlang.org/ https://github.com/cirorizzo/KShows https://github.com/cirorizzo/JShows