SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
Kotlin Features
for Android Developers
What is Kotlin?
● Kotlin is not a platform (Xamarin, Cordova, etc.)
● It’s more like TypeScript or Swift
● Kotlin is a programing language built to run wherever Java runs
● It’s a pragmatic language, designed for developer productivity
Painless Java Interop
● Kotlin was build to play nicely with Java
● Mix Java and Kotlin code in the same project
● You can still use all your favorite libraries in Kotlin
● The underlying Android Framework is the exact same
you would use in Java
Project Setup
1. Install the IDE plugin
Project Setup
2. Add the dependencies
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin-android'
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
Basic Syntax Overview
// in Kotlin types go at the end
var a: String = "Hello"
fun sayHello(): String {
return "Hello"
}
class MyActivity: Activity()
// Java equivalent
String a = "hello";
String sayHello() {
return "Hello";
}
class MyActivity extends Activity {
}
Basic Syntax Overview
// in Kotlin
val a = 1
a = 2 // ← compiler error
var b = 1
b = 2 // ← this is ok
fun c() {
}
// Java equivalent
final int a = 1;
a = 2; // ← compiler error
int b = 1;
b = 2; // ← this is ok
void c() {
}
Features you can use from day 1
1. Null safety and Smart Cast
Nullability is part of the type system and enforced by the compiler
val a: String = null // ← syntax error
val a: String? = null // ← this is ok
1. Null safety and Smart Cast
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
savedInstanceState.getString(...) // ← syntax error
savedInstanceState?.getString(...) // ← this is ok
savedInstanceState!!.getString(...) // ← this is also ok but will
// throw on null
}
1. Null safety and Smart Cast
Once the compiler determines a value can't be null, you can use it as such
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(savedInstanceState != null) {
// The compiler now knows it can't be null here
savedInstanceState.getString(...)
savedInstanceState.getInt(...)
}
}
1. Null safety and Smart Cast
We can use the “Elvis Operator” to provide default values
// in Kotlin
val someValue = savedInstanceState?.getString("value") ?: "default"
// Java equivalent
String someValue;
If (savedInstanceState != null &&
savedInstanceState.getString("value") != null) {
someValue = savedInstanceState.getString("value");
} else {
someValue = "default";
}
2. Statements as expressions
In Kotlin statements like if and when can be used as expressions
override fun getItemViewType(position: Int): Int {
return when(items[position]) {
is Title -> TYPE_TITLE
is Description -> TYPE_DESCRIPTION
else -> TYPE_UNKNOWN
}
}
2. Statements as expressions
return and throw are also expressions but return the Nothing type
fun renderWeatherCondition(condition: WeatherCondition?) {
val iconRes = if (condition != null) {
when (condition.type) {
SUNNY -> R.drawable.ic_sunny
RAINY -> R.drawable.ic_rainy
else -> throw RuntimeException("Unknown condition $condition")
}
} else {
return
}
//...
}
3. Inline methods and lambdas
The Kotlin stdlib comes with a set of quite useful functional operations
val titles = movieList
.filter { it.isFavorite }
.sortedByDescending { it.rating }
.map { it.title }
// Java equivalent
List<Movie> favoriteMovies = new ArrayList<>();
for (Movie movie : movieList) {
if(movie.isFavorite()) {
favoriteMovies.add(movie);
}
}
Collections.sort(favoriteMovies, new Comparator<Movie>() {
@Override
public int compare(Movie o1, Movie o2) {
return o1.getRating() - o2.getRating();
}
});
List<String> titles = new ArrayList<>();
for (Movie movie : favoriteMovies) {
titles.add(movie.getTitle());
}
3. Inline methods and lambdas
● Methods in Kotlin can be marked as inline
● The body of the inline method is “copied” to the call site
● Lambdas in these methods generate no overhead
inline fun <T> Iterable<T>.forEach(action: (T) -> Unit) {
for (element in this) action(element)
}
In Kotlin you can define functions what act on a specific receiver type
4. Extension functions
fun Context.getDrawableCompat(resId: Int): Drawable {
return ContextCompat.getDrawable(this, resId)
}
val logo = context.getDrawableCompat(R.drawable.ic_logo)
4. Extension functions
fun Context.share(text: String, subject: String = "") {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, text)
startActivity(Intent.createChooser(intent, null))
}
Some more advanced features
5. Reified generics
Kotlin has limited support for reified generics
// in Java
List<User> users = gson.fromJson(json, new TypeToken<List<User>>() {}.getType());
// in Kotlin
inline fun <reified T> Gson.fromJson(json: String): T {
return fromJson(json, T::class.java)
}
val users = gson.fromJson<List<User>>(json)
6. Receiver lambdas
● Lambda parameters can be defined with an optional receiver type
● Code inside these lambdas behaves as if defined in an extension function on
that type
inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_SUBJECT, "Hi!")
putExtra(Intent.EXTRA_TEXT, "Hello")
}
6. Receiver lambdas
// in Java
db.beginTransaction();
try {
db.insert(...);
db.update(...);
db.delete(...);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
6. Receiver lambdas
fun SQLiteDatabase.inTransaction(block: SQLiteDatabase.() -> Unit) {
beginTransaction();
try {
block()
setTransactionSuccessful();
} finally {
endTransaction();
}
}
6. Receiver lambdas
//in Kotlin
db.inTransaction {
insert(...)
update(...)
delete(...)
}
// Java equivalent
db.beginTransaction();
try {
db.insert(...);
db.update(...);
db.delete(...);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
6. Receiver lambdas
This feature is very useful for creating DSLs
val layout = verticalLayout {
padding = dip(30)
editText {
hint = "Name"
textSize = 24f
}
editText {
hint = "Password"
textSize = 24f
}
button("Login") {
textSize = 26f
}
}
Upcoming in 1.1 - Coroutines
showLoading()
val someOperation = async { complicatedOperation() }
val anotherOperation = async { complicatedOperation() }
val result = someOperation.await() + anotherOperation.await()
displayResult(result)
hideLoading()
Much more that we didn’t cover
● Property delegation
● Data classes
● Sealed classes
● Type aliases
● Operator overloading
● Destructuring operators
● Infix functions
● Named parameters
● Class delegation
● … and more
Resources
● Official website: http://kotlinlang.org
● Online “IDE”: http://try.kotl.in
● Official Slack: http://slack.kotlinlang.org (~6000 members and counting)
● GitHub repo: https://github.com/jetbrains/kotlin
● “Design documents” for upcoming features: https://github.com/Kotlin/KEEP

Weitere ähnliche Inhalte

Was ist angesagt?

Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
Andrzej Sitek
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
intelliyole
 

Was ist angesagt? (19)

The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
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
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
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 boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
 
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...
 
Summer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcampSummer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcamp
 
2017: Kotlin - now more than ever
2017: Kotlin - now more than ever2017: Kotlin - now more than ever
2017: Kotlin - now more than ever
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
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?
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 

Andere mochten auch

resume Kar Fong2014
resume Kar Fong2014resume Kar Fong2014
resume Kar Fong2014
Kar Fong leh
 

Andere mochten auch (16)

Kotlin на практике
Kotlin на практикеKotlin на практике
Kotlin на практике
 
RxJava - Programação assíncrona para Android.
RxJava - Programação assíncrona para Android.RxJava - Programação assíncrona para Android.
RxJava - Programação assíncrona para Android.
 
"Inspectorul Padurii" mobile app - Bogdan Micu
 "Inspectorul Padurii" mobile app - Bogdan Micu "Inspectorul Padurii" mobile app - Bogdan Micu
"Inspectorul Padurii" mobile app - Bogdan Micu
 
Tejido muscular
Tejido muscularTejido muscular
Tejido muscular
 
resume Kar Fong2014
resume Kar Fong2014resume Kar Fong2014
resume Kar Fong2014
 
Eldinero
EldineroEldinero
Eldinero
 
KEWIRAUSAHAAN - Karakteristik Wirausahawan
KEWIRAUSAHAAN - Karakteristik WirausahawanKEWIRAUSAHAAN - Karakteristik Wirausahawan
KEWIRAUSAHAAN - Karakteristik Wirausahawan
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
 
Azure for Android Developers
Azure for Android Developers Azure for Android Developers
Azure for Android Developers
 
Haitham cv
Haitham cvHaitham cv
Haitham cv
 
Madalina Seghete, Branch Metrics, presentation on app virality
Madalina Seghete, Branch Metrics, presentation on  app viralityMadalina Seghete, Branch Metrics, presentation on  app virality
Madalina Seghete, Branch Metrics, presentation on app virality
 
Theodolite and its working mechanism
Theodolite and its working mechanismTheodolite and its working mechanism
Theodolite and its working mechanism
 
Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
 
Groovy Powered Clean Code
Groovy Powered Clean CodeGroovy Powered Clean Code
Groovy Powered Clean Code
 
Groovy on Android
Groovy on AndroidGroovy on Android
Groovy on Android
 
UNCRC poster for children
UNCRC poster for childrenUNCRC poster for children
UNCRC poster for children
 

Ähnlich wie Kotlin for Android - Vali Iorgu - mRready

Kotlin what_you_need_to_know-converted event 4 with nigerians
Kotlin  what_you_need_to_know-converted event 4 with nigeriansKotlin  what_you_need_to_know-converted event 4 with nigerians
Kotlin what_you_need_to_know-converted event 4 with nigerians
junaidhasan17
 

Ähnlich wie Kotlin for Android - Vali Iorgu - mRready (20)

What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Practical tips for building apps with kotlin
Practical tips for building apps with kotlinPractical tips for building apps with kotlin
Practical tips for building apps with kotlin
 
Save time with kotlin in android development
Save time with kotlin in android developmentSave time with kotlin in android development
Save time with kotlin in android development
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo Surabaya
 
從零開始學 Android
從零開始學 Android從零開始學 Android
從零開始學 Android
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Kotlin what_you_need_to_know-converted event 4 with nigerians
Kotlin  what_you_need_to_know-converted event 4 with nigeriansKotlin  what_you_need_to_know-converted event 4 with nigerians
Kotlin what_you_need_to_know-converted event 4 with nigerians
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
 
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
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
Programming with Kotlin
Programming with KotlinProgramming with Kotlin
Programming with Kotlin
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Compose Camp Day 3 PPT.pptx.pdf
Compose Camp Day 3 PPT.pptx.pdfCompose Camp Day 3 PPT.pptx.pdf
Compose Camp Day 3 PPT.pptx.pdf
 
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
 

Mehr von MobileAcademy (7)

Questo presentation @ mobile growth meetup Bucharest
Questo presentation @ mobile growth meetup BucharestQuesto presentation @ mobile growth meetup Bucharest
Questo presentation @ mobile growth meetup Bucharest
 
Ludicon presentation @ mobile growth meetup Romania
Ludicon presentation @ mobile growth meetup RomaniaLudicon presentation @ mobile growth meetup Romania
Ludicon presentation @ mobile growth meetup Romania
 
Push notifications at scale
Push notifications at scalePush notifications at scale
Push notifications at scale
 
MVVM with RxJava
MVVM with RxJavaMVVM with RxJava
MVVM with RxJava
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation
 
Rares Serban, Sr. Mobile Developer at Soft to you - cross-platform development
Rares Serban, Sr. Mobile Developer at Soft to you - cross-platform developmentRares Serban, Sr. Mobile Developer at Soft to you - cross-platform development
Rares Serban, Sr. Mobile Developer at Soft to you - cross-platform development
 
Bucharest City App presentation @MobileAcademy Meetup #2
Bucharest City App presentation @MobileAcademy Meetup #2Bucharest City App presentation @MobileAcademy Meetup #2
Bucharest City App presentation @MobileAcademy Meetup #2
 

Kürzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Kotlin for Android - Vali Iorgu - mRready

  • 2. What is Kotlin? ● Kotlin is not a platform (Xamarin, Cordova, etc.) ● It’s more like TypeScript or Swift ● Kotlin is a programing language built to run wherever Java runs ● It’s a pragmatic language, designed for developer productivity
  • 3. Painless Java Interop ● Kotlin was build to play nicely with Java ● Mix Java and Kotlin code in the same project ● You can still use all your favorite libraries in Kotlin ● The underlying Android Framework is the exact same you would use in Java
  • 4. Project Setup 1. Install the IDE plugin
  • 5. Project Setup 2. Add the dependencies buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: 'kotlin-android' dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" }
  • 6. Basic Syntax Overview // in Kotlin types go at the end var a: String = "Hello" fun sayHello(): String { return "Hello" } class MyActivity: Activity() // Java equivalent String a = "hello"; String sayHello() { return "Hello"; } class MyActivity extends Activity { }
  • 7. Basic Syntax Overview // in Kotlin val a = 1 a = 2 // ← compiler error var b = 1 b = 2 // ← this is ok fun c() { } // Java equivalent final int a = 1; a = 2; // ← compiler error int b = 1; b = 2; // ← this is ok void c() { }
  • 8. Features you can use from day 1
  • 9. 1. Null safety and Smart Cast Nullability is part of the type system and enforced by the compiler val a: String = null // ← syntax error val a: String? = null // ← this is ok
  • 10. 1. Null safety and Smart Cast override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState.getString(...) // ← syntax error savedInstanceState?.getString(...) // ← this is ok savedInstanceState!!.getString(...) // ← this is also ok but will // throw on null }
  • 11. 1. Null safety and Smart Cast Once the compiler determines a value can't be null, you can use it as such override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if(savedInstanceState != null) { // The compiler now knows it can't be null here savedInstanceState.getString(...) savedInstanceState.getInt(...) } }
  • 12. 1. Null safety and Smart Cast We can use the “Elvis Operator” to provide default values // in Kotlin val someValue = savedInstanceState?.getString("value") ?: "default" // Java equivalent String someValue; If (savedInstanceState != null && savedInstanceState.getString("value") != null) { someValue = savedInstanceState.getString("value"); } else { someValue = "default"; }
  • 13. 2. Statements as expressions In Kotlin statements like if and when can be used as expressions override fun getItemViewType(position: Int): Int { return when(items[position]) { is Title -> TYPE_TITLE is Description -> TYPE_DESCRIPTION else -> TYPE_UNKNOWN } }
  • 14. 2. Statements as expressions return and throw are also expressions but return the Nothing type fun renderWeatherCondition(condition: WeatherCondition?) { val iconRes = if (condition != null) { when (condition.type) { SUNNY -> R.drawable.ic_sunny RAINY -> R.drawable.ic_rainy else -> throw RuntimeException("Unknown condition $condition") } } else { return } //... }
  • 15. 3. Inline methods and lambdas The Kotlin stdlib comes with a set of quite useful functional operations val titles = movieList .filter { it.isFavorite } .sortedByDescending { it.rating } .map { it.title } // Java equivalent List<Movie> favoriteMovies = new ArrayList<>(); for (Movie movie : movieList) { if(movie.isFavorite()) { favoriteMovies.add(movie); } } Collections.sort(favoriteMovies, new Comparator<Movie>() { @Override public int compare(Movie o1, Movie o2) { return o1.getRating() - o2.getRating(); } }); List<String> titles = new ArrayList<>(); for (Movie movie : favoriteMovies) { titles.add(movie.getTitle()); }
  • 16. 3. Inline methods and lambdas ● Methods in Kotlin can be marked as inline ● The body of the inline method is “copied” to the call site ● Lambdas in these methods generate no overhead inline fun <T> Iterable<T>.forEach(action: (T) -> Unit) { for (element in this) action(element) }
  • 17. In Kotlin you can define functions what act on a specific receiver type 4. Extension functions fun Context.getDrawableCompat(resId: Int): Drawable { return ContextCompat.getDrawable(this, resId) } val logo = context.getDrawableCompat(R.drawable.ic_logo)
  • 18. 4. Extension functions fun Context.share(text: String, subject: String = "") { val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra(Intent.EXTRA_SUBJECT, subject) intent.putExtra(Intent.EXTRA_TEXT, text) startActivity(Intent.createChooser(intent, null)) }
  • 19. Some more advanced features
  • 20. 5. Reified generics Kotlin has limited support for reified generics // in Java List<User> users = gson.fromJson(json, new TypeToken<List<User>>() {}.getType()); // in Kotlin inline fun <reified T> Gson.fromJson(json: String): T { return fromJson(json, T::class.java) } val users = gson.fromJson<List<User>>(json)
  • 21. 6. Receiver lambdas ● Lambda parameters can be defined with an optional receiver type ● Code inside these lambdas behaves as if defined in an extension function on that type inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this } val intent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_SUBJECT, "Hi!") putExtra(Intent.EXTRA_TEXT, "Hello") }
  • 22. 6. Receiver lambdas // in Java db.beginTransaction(); try { db.insert(...); db.update(...); db.delete(...); db.setTransactionSuccessful(); } finally { db.endTransaction(); }
  • 23. 6. Receiver lambdas fun SQLiteDatabase.inTransaction(block: SQLiteDatabase.() -> Unit) { beginTransaction(); try { block() setTransactionSuccessful(); } finally { endTransaction(); } }
  • 24. 6. Receiver lambdas //in Kotlin db.inTransaction { insert(...) update(...) delete(...) } // Java equivalent db.beginTransaction(); try { db.insert(...); db.update(...); db.delete(...); db.setTransactionSuccessful(); } finally { db.endTransaction(); }
  • 25. 6. Receiver lambdas This feature is very useful for creating DSLs val layout = verticalLayout { padding = dip(30) editText { hint = "Name" textSize = 24f } editText { hint = "Password" textSize = 24f } button("Login") { textSize = 26f } }
  • 26. Upcoming in 1.1 - Coroutines showLoading() val someOperation = async { complicatedOperation() } val anotherOperation = async { complicatedOperation() } val result = someOperation.await() + anotherOperation.await() displayResult(result) hideLoading()
  • 27. Much more that we didn’t cover ● Property delegation ● Data classes ● Sealed classes ● Type aliases ● Operator overloading ● Destructuring operators ● Infix functions ● Named parameters ● Class delegation ● … and more
  • 28. Resources ● Official website: http://kotlinlang.org ● Online “IDE”: http://try.kotl.in ● Official Slack: http://slack.kotlinlang.org (~6000 members and counting) ● GitHub repo: https://github.com/jetbrains/kotlin ● “Design documents” for upcoming features: https://github.com/Kotlin/KEEP