SlideShare a Scribd company logo
1 of 29
Download to read offline
Developing
Android apps
with Kotlin
AVGeeks, June 2016
Shem Magnezi
Shem Magnezi
@shemag8 | shem8.github.com
Java is great
▣ Very popular.
▣ Great community.
▣ Lots of frameworks and libraries.
▣ Supported by big companies (Oracle &
Google).
▣ Portable, fast, well documented.
▣ Great IDEs
▣ You can write server side, web and mobile.
Yes but...
▣ Lot’s of boilerplate
▣ Null checks
▣ Exception handling
▣ Function pointers
▣ Data classes (POJO)
▣ Extension functions
▣ Operator overloading
▣ String interpolation
▣ And more...
On Android it even worse
▣ Barely support Java 8 (N+)
▣ Partially support Java 7 (KitKat+)
▣ There are some libraries that fill some of the
missing features (retro lambda, RX, etc..) but
it’s not the same.
▣ It mainly feel too ‘heavy’ for front end code.
Kotlin
Statically typed programming language
for the JVM, Android and the browser
100% interoperable with Java™
Kotlin?
▣ Open source, lead by JetBrains.
▣ JVM language (Like Scala, Groovy and Clojure)
▣ Can call Java code and vice versa.
▣ Fully integrated IDE.
▣ Small (600KB before ProGuard).
▣ Statically typed so no runtime overhead.
▣ Used by a lot of big companies, even by the
Android team (data binding).
Code!
1.
Basic syntax
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
fun mul(x: Int, y: Int = 2): Int {
return x * y
}
fun mul(x: Int, y: Int = 2) = x * y
view.setOnClickListener({ //click handling })
if (obj is String) {
print(obj.length)
}
val items = listOf(1, 2, 3, 4)
items.first() == 1
items.last() == 4
items.filter { it % 2 == 0 } // returns [2, 4]
ints.forEach {
if (it == 0) return
print(it)
}
2.
Null Safety
‘’
I call it my billion-dollar mistake. It
was the invention of the null
reference in 1965 ... My goal was to
ensure that all use of references
should be absolutely safe... This has
led to innumerable errors,
vulnerabilities, and system crashes,
which have probably caused a
billion dollars of pain and damage in
the last forty years.
Tony Hoare
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
val l = b?.length ?: -1
3.
Data Classes
data class User(val name: String, val age: Int)
You get for free:
▣ equals()
▣ hashCode()
▣ toString() of the form "User(name=John, age=42)",
▣ copy() function
▣ getters()
4.
Extensions
Functions
fun Date.isThuesday() Boolean {
return day == 2
}
if (date.isTuesday) {
...
}
fun Date.isThuesday() = day == 2
fun SQLiteDatabase.inTransaction(func: () -> Unit) {
beginTransaction()
try {
func()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
db.inTransaction {
}
fun AppCompatActivity.navigate(frag: Fragment) {
val fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.replace(content.id, frag);
fragmentTransaction.commit();
}
fun Fragment.userError(msg: String?) {
Snackbar.make(view, msg, Snackbar.LENGTH_LONG).show()
}
fun SharedPreferences.edit(func:SharedPreferences.Editor.(): Unit) {
val editor = edit()
editor.func()
editor.apply()
}
fun SharedPreferences.Editor.set(pair: Pair<String, String>) = putString(pair.first, pair.second)
preferences.edit {
set("foo" to "bar")
set("fizz" to "buzz")
remove("username")
}
inline fun <T: View> T.afterMeasured(crossinline f: T.() -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
f()
}
}
})
}
recycler.afterMeasured {
val columnCount = width / columnWidth
layoutManager = GridLayoutManager(context, columnCount)
}
5.
Android
Extensions
// Using R.layout.activity_main from the main source set
import kotlinx.android.synthetic.main.activity_main.*
public class MyActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView.setText("Hello, world!") // Instead of findView(R.id.textView) as TextView
}
}
6.
Anko library
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
verticalLayout {
padding = dip(30)
editText {
hint = "Name"
textSize = 24f
}
editText {
hint = "Password"
textSize = 24f
}
button("Login") {
textSize = 26f
}
}
}
There is much more:
▣ kotlinlang.org
▣ blog.jetbrains.com/kotlin
▣ kotlinlang.org/docs/resources.html
▣ Kara- An MVC Framework
▣ Android Kotlin Extensions- A collection of Android Kotlin
extensions
▣ KAndroid- Kotlin library for Android
▣ Anko- Pleasant Android application development
Thanks!
Any questions?
You can find this presentation at: shem8.github.io
smagnezi8@gmail.com
Presentation template by SlidesCarnival | Photographs by Unsplash
Credits
Android Development with Kotlin - Jake Wharton
Droidcon SF - Better Android Development with Kotlin and
Gradle
Special thanks to all the people who made and released these
awesome resources for free:
▣ Presentation template by SlidesCarnival
▣ Photographs by Unsplash

More Related Content

What's hot

EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
Heiko Behrens
 
MDSD for iPhone and Android
MDSD for iPhone and AndroidMDSD for iPhone and Android
MDSD for iPhone and Android
Heiko Behrens
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
Kiyotaka Oku
 

What's hot (20)

EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Webbeyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
 
Architectures in the compose world
Architectures in the compose worldArchitectures in the compose world
Architectures in the compose world
 
안드로이드 데이터 바인딩
안드로이드 데이터 바인딩안드로이드 데이터 바인딩
안드로이드 데이터 바인딩
 
MDSD for iPhone and Android
MDSD for iPhone and AndroidMDSD for iPhone and Android
MDSD for iPhone and Android
 
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
JCConf 2015  - 輕鬆學google的雲端開發 - Google App Engine入門(上)JCConf 2015  - 輕鬆學google的雲端開發 - Google App Engine入門(上)
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
descriptive programming
descriptive programmingdescriptive programming
descriptive programming
 
Cnam azure 2014 mobile services
Cnam azure 2014   mobile servicesCnam azure 2014   mobile services
Cnam azure 2014 mobile services
 
How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)
 
droidQuery: The Android port of jQuery
droidQuery: The Android port of jQuerydroidQuery: The Android port of jQuery
droidQuery: The Android port of jQuery
 
GreenDao Introduction
GreenDao IntroductionGreenDao Introduction
GreenDao Introduction
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
 
Kotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community confKotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community conf
 
Mongo db for C# Developers
Mongo db for C# DevelopersMongo db for C# Developers
Mongo db for C# Developers
 
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere StockholmKotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere Stockholm
 
Green dao
Green daoGreen dao
Green dao
 
Green dao
Green daoGreen dao
Green dao
 

Similar to Building android apps with kotlin

Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
Peter Higgins
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
Yuren Ju
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 

Similar to Building android apps with kotlin (20)

What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Java
JavaJava
Java
 
Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
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
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
mobl
moblmobl
mobl
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Kotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platforms
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Let's Go-lang
Let's Go-langLet's Go-lang
Let's Go-lang
 
jQuery
jQueryjQuery
jQuery
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 

More from Shem Magnezi

More from Shem Magnezi (13)

The Future of Work(ers)
The Future of Work(ers)The Future of Work(ers)
The Future of Work(ers)
 
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...
 
Good rules for bad apps
Good rules for bad appsGood rules for bad apps
Good rules for bad apps
 
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...
 
Iterating on your idea
Iterating on your ideaIterating on your idea
Iterating on your idea
 
The Redux State of the Art
The Redux State of the ArtThe Redux State of the Art
The Redux State of the Art
 
Startup hackers toolbox
Startup hackers toolboxStartup hackers toolbox
Startup hackers toolbox
 
Fuck you startup world
Fuck you startup worldFuck you startup world
Fuck you startup world
 
The Future of Work
The Future of WorkThe Future of Work
The Future of Work
 
Good rules for bad apps
Good rules for bad appsGood rules for bad apps
Good rules for bad apps
 
Andriod dev toolbox part 2
Andriod dev toolbox  part 2Andriod dev toolbox  part 2
Andriod dev toolbox part 2
 
Know what (not) to build
Know what (not) to buildKnow what (not) to build
Know what (not) to build
 
Android ui tips & tricks
Android ui tips & tricksAndroid ui tips & tricks
Android ui tips & tricks
 

Recently uploaded

+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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

+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...
 
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 🔝✔️✔️
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
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...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
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 🔝✔️✔️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
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
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 

Building android apps with kotlin

  • 2. Shem Magnezi @shemag8 | shem8.github.com
  • 3. Java is great ▣ Very popular. ▣ Great community. ▣ Lots of frameworks and libraries. ▣ Supported by big companies (Oracle & Google). ▣ Portable, fast, well documented. ▣ Great IDEs ▣ You can write server side, web and mobile.
  • 4. Yes but... ▣ Lot’s of boilerplate ▣ Null checks ▣ Exception handling ▣ Function pointers ▣ Data classes (POJO) ▣ Extension functions ▣ Operator overloading ▣ String interpolation ▣ And more...
  • 5. On Android it even worse ▣ Barely support Java 8 (N+) ▣ Partially support Java 7 (KitKat+) ▣ There are some libraries that fill some of the missing features (retro lambda, RX, etc..) but it’s not the same. ▣ It mainly feel too ‘heavy’ for front end code.
  • 6. Kotlin Statically typed programming language for the JVM, Android and the browser 100% interoperable with Java™
  • 7. Kotlin? ▣ Open source, lead by JetBrains. ▣ JVM language (Like Scala, Groovy and Clojure) ▣ Can call Java code and vice versa. ▣ Fully integrated IDE. ▣ Small (600KB before ProGuard). ▣ Statically typed so no runtime overhead. ▣ Used by a lot of big companies, even by the Android team (data binding).
  • 10. when (x) { in 1..10 -> print("x is in the range") in validNumbers -> print("x is valid") !in 10..20 -> print("x is outside the range") else -> print("none of the above") } fun mul(x: Int, y: Int = 2): Int { return x * y } fun mul(x: Int, y: Int = 2) = x * y view.setOnClickListener({ //click handling })
  • 11. if (obj is String) { print(obj.length) } val items = listOf(1, 2, 3, 4) items.first() == 1 items.last() == 4 items.filter { it % 2 == 0 } // returns [2, 4] ints.forEach { if (it == 0) return print(it) }
  • 13. ‘’ I call it my billion-dollar mistake. It was the invention of the null reference in 1965 ... My goal was to ensure that all use of references should be absolutely safe... This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years. Tony Hoare
  • 14. var a: String = "abc" a = null // compilation error var b: String? = "abc" b = null // ok val l = b?.length ?: -1
  • 16. data class User(val name: String, val age: Int) You get for free: ▣ equals() ▣ hashCode() ▣ toString() of the form "User(name=John, age=42)", ▣ copy() function ▣ getters()
  • 18. fun Date.isThuesday() Boolean { return day == 2 } if (date.isTuesday) { ... } fun Date.isThuesday() = day == 2
  • 19. fun SQLiteDatabase.inTransaction(func: () -> Unit) { beginTransaction() try { func() setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { }
  • 20. fun AppCompatActivity.navigate(frag: Fragment) { val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.replace(content.id, frag); fragmentTransaction.commit(); } fun Fragment.userError(msg: String?) { Snackbar.make(view, msg, Snackbar.LENGTH_LONG).show() }
  • 21. fun SharedPreferences.edit(func:SharedPreferences.Editor.(): Unit) { val editor = edit() editor.func() editor.apply() } fun SharedPreferences.Editor.set(pair: Pair<String, String>) = putString(pair.first, pair.second) preferences.edit { set("foo" to "bar") set("fizz" to "buzz") remove("username") }
  • 22. inline fun <T: View> T.afterMeasured(crossinline f: T.() -> Unit) { viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (measuredWidth > 0 && measuredHeight > 0) { viewTreeObserver.removeOnGlobalLayoutListener(this) f() } } }) } recycler.afterMeasured { val columnCount = width / columnWidth layoutManager = GridLayoutManager(context, columnCount) }
  • 24. // Using R.layout.activity_main from the main source set import kotlinx.android.synthetic.main.activity_main.* public class MyActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView.setText("Hello, world!") // Instead of findView(R.id.textView) as TextView } }
  • 26. override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) verticalLayout { padding = dip(30) editText { hint = "Name" textSize = 24f } editText { hint = "Password" textSize = 24f } button("Login") { textSize = 26f } } }
  • 27. There is much more: ▣ kotlinlang.org ▣ blog.jetbrains.com/kotlin ▣ kotlinlang.org/docs/resources.html ▣ Kara- An MVC Framework ▣ Android Kotlin Extensions- A collection of Android Kotlin extensions ▣ KAndroid- Kotlin library for Android ▣ Anko- Pleasant Android application development
  • 28. Thanks! Any questions? You can find this presentation at: shem8.github.io smagnezi8@gmail.com Presentation template by SlidesCarnival | Photographs by Unsplash
  • 29. Credits Android Development with Kotlin - Jake Wharton Droidcon SF - Better Android Development with Kotlin and Gradle Special thanks to all the people who made and released these awesome resources for free: ▣ Presentation template by SlidesCarnival ▣ Photographs by Unsplash