SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin PresentationAndrzej Sitek
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyMobileAcademy
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyHaim Yadid
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinKai Koenig
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017Hardik Trivedi
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivitynklmish
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?intelliyole
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinKai Koenig
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene BurmakoVasil Remeniuk
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java DevelopersChristoph Pickl
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devsAdit Lal
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Andrey Breslav
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performanceintelliyole
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan s.r.o.
 

Tendances (19)

Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, Seriously
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with Kotlin
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
 
Kotlin
KotlinKotlin
Kotlin
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with Kotlin
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
 

En vedette

A brief introduction to Realm with Kotlin
A brief introduction to Realm with KotlinA brief introduction to Realm with Kotlin
A brief introduction to Realm with KotlinLeonardo YongUk Kim
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»e-Legion
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers STX Next
 
Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Omar Miatello
 
Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Omar Miatello
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
Exploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, AndroidExploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, AndroidRakshak R.Hegde
 
Дмитрий Юницкий. «Android NDK или как я перестал бояться и полюбил нативную р...
Дмитрий Юницкий. «Android NDK или как я перестал бояться и полюбил нативную р...Дмитрий Юницкий. «Android NDK или как я перестал бояться и полюбил нативную р...
Дмитрий Юницкий. «Android NDK или как я перестал бояться и полюбил нативную р...Mail.ru Group
 
The Shape of Functional Programming
The Shape of Functional ProgrammingThe Shape of Functional Programming
The Shape of Functional ProgrammingMike Fogus
 
Introduction to Zeder - a production rules toolkit for Clojure
Introduction to Zeder - a production rules toolkit for ClojureIntroduction to Zeder - a production rules toolkit for Clojure
Introduction to Zeder - a production rules toolkit for ClojureMike Fogus
 
The Macronomicon
The MacronomiconThe Macronomicon
The MacronomiconMike Fogus
 
ClojureScript Anatomy
ClojureScript AnatomyClojureScript Anatomy
ClojureScript AnatomyMike Fogus
 
Getting started-kotlin-android
Getting started-kotlin-androidGetting started-kotlin-android
Getting started-kotlin-androidLucas Albuquerque
 
Fertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureFertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureMike Fogus
 
いまさら聞けないRake入門
いまさら聞けないRake入門いまさら聞けないRake入門
いまさら聞けないRake入門Tomoya Kawanishi
 
The Return of the Living Datalog
The Return of the Living DatalogThe Return of the Living Datalog
The Return of the Living DatalogMike Fogus
 
SeaJUG May 2012 mybatis
SeaJUG May 2012 mybatisSeaJUG May 2012 mybatis
SeaJUG May 2012 mybatisWill Iverson
 
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...Altoros
 

En vedette (20)

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

Similaire à Kotlin in action

Programming with Kotlin
Programming with KotlinProgramming with Kotlin
Programming with KotlinDavid Gassner
 
GDG Kuwait - Modern android development
GDG Kuwait - Modern android developmentGDG Kuwait - Modern android development
GDG Kuwait - Modern android developmentGDGKuwaitGoogleDevel
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android UpdateGarth Gilmour
 
Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?Kai Koenig
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseChristian Melchior
 
Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android DevelopmentSpeck&Tech
 
Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)Hassan Abid
 
Rapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorRapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorTrayan Iliev
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of androidDJ Rausch
 
Scala on-android
Scala on-androidScala on-android
Scala on-androidlifecoder
 
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 Fall
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 FallJavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 Fall
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 FallYuichi Sakuraba
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016STX Next
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)DroidConTLV
 
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDevKotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDevDroidConTLV
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with KotlinMurat Yener
 
Dependency Injections in Kotlin
Dependency Injections in KotlinDependency Injections in Kotlin
Dependency Injections in KotlinEatDog
 
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android ExtensionsReducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android ExtensionsPatrick Steiger
 

Similaire à Kotlin in action (20)

Programming with Kotlin
Programming with KotlinProgramming with Kotlin
Programming with Kotlin
 
GDG Kuwait - Modern android development
GDG Kuwait - Modern android developmentGDG Kuwait - Modern android development
GDG Kuwait - Modern android development
 
Fall in love with Kotlin
Fall in love with KotlinFall in love with Kotlin
Fall in love with Kotlin
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
Kotlin wonderland
Kotlin wonderlandKotlin wonderland
Kotlin wonderland
 
Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
 
Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)
 
Rapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorRapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and Ktor
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of android
 
Scala on-android
Scala on-androidScala on-android
Scala on-android
 
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 Fall
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 FallJavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 Fall
JavaOne報告会 Java SE/JavaFX 編 - JJUG CCC 2010 Fall
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDevKotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with Kotlin
 
Dependency Injections in Kotlin
Dependency Injections in KotlinDependency Injections in Kotlin
Dependency Injections in Kotlin
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
 
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android ExtensionsReducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
 

Dernier

Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
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 insideshinachiaurasa2
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
%+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
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
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 🔝✔️✔️Delhi Call girls
 
%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 kaalfonteinmasabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
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...Bert Jan Schrijver
 
%+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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 

Dernier (20)

Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
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
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%+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...
 
+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...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
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 🔝✔️✔️
 
%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
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
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...
 
%+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...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

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