SlideShare a Scribd company logo
Introduction to Kotlin language & its
application to Android platform
Overview
What is Kotlin
• Kotlin is a new programming language by Jetbrains.
• It runs on JVM stack.
• It has ≈zero-cost Java interop.
• It runs on Android, easily.
Let’s go!
• Kotlin is a new programming language by Jetbrains.
• It runs on JVM stack.
• It has ≈zero-cost Java interop.
• It runs on Android, easily.
Hello, world!
fun main(args: Array<String>) {
println("Hello, world!")
}
Hello, world!
fun main(args: Array<String>) =
println("Hello, world!")
Hello, world!
fun main(args: Array<String>) =
args.joinToString(postfix = "!")
.forEach { print(it) }
> kotlin HelloKt Hello world
Why Kotlin?
• Concise — write less boilerplate.
• Interoperable — write alongside your Java code.
• Multi-paradigm — you can write functional-alike code.
• Promising — developed by developers for developers.
• It runs on Android, easily!
Kotlin on Android
Why Kotlin?
• Android runs using fork of Apache Harmony (≈Java 6).
• Starting from Android API 19 (Android 4.4) it supports Java 7 features.
• Android N (Nutella? 6.1?) brings support for Java 8.
• But it is still Java…
Why Kotlin?
• There are lot of modern features and approaches that are unavailable
even in Java 8.
• Typical Java code is bloated, has a lot of boilerplate.
• Kotlin is much more expressive than Java.
Why Kotlin?
final Config config = playlist.getConfig();
if (config != null && config.getUrls() != null) {
for (final Url url : config.getUrls()) {
if (url.getFormat().equals("txt")) {
this.url = url;
}
}
}
Why Kotlin?
playlist.config?.urls
?.firstOrNull { it.format == "txt" }
?.let { this.url = it.url }
Kotlin features
Null safety
• You won’t see NPE anymore (unless you want)
• In pure Kotlin, you can have something non-null:
• var foo: String = "foo"
• Or nullable
• var bar: String? = "bar"
• Then:
• foo = null → compilation error
• bar = null → OK
Null safety
• var foo: String = "foo"
• var bar: String? = "bar"
• foo.length → 3
• bar.length → ???
Null safety
• var foo: String = "foo"
• var bar: String? = "bar"
• foo.length → 3
• bar.length → compilation error
• Call is null-unsafe, there are two methods to fix it:
• bar?.length → 3 (or null if bar == null)
• bar!!.length → 3 (or NPE if bar == null)
Null safety
• var foo: String = "foo"
• var bar: String? = "bar"
• if (bar != null) {
• // bar is effectively not null, it can be treated as String, not String?
• bar.length → 3
• }
Null safety
• Kotlin understands lot of Java annotations for null-safety (JSR-308,
Guava, Android, Jetbrains, etc.)
• If nothing is specified, you can treat Java object as Nullable
Null safety
• Kotlin understands lot of Java annotations for null-safety (JSR-308,
Guava, Android, Jetbrains, etc.)
• If nothing is specified, you can treat Java object as Nullable
• Or NotNull!
• It’s up to you, and you should take care of proper handling nulls.
Type inference
• var bar: CharSequence? = "bar"
• if (bar != null && bar is String) {
• // bar can be treated as String without implicit conversion
• bar.length → 3
• }
Type inference
• fun List.reversed() = Collections.reverse(list)
• Return type List is inferred automatically
• //effectively fun List.reversed() : List = Collections.reverse(list)
Lambdas
• Kotlin has it
• And it helps a lot
• Works fine for SAM
Lambdas
strings
.filter( { it.count { it in "aeiou" } >= 3 } )
.filterNot { it.contains("ab|cd|pq|xy".toRegex()) }
.filter { s -> s.contains("([a-z])1".toRegex()) }
.size.toString()
Lambdas
• Can be in-lined.
• Can use anonymous class if run on JVM 6.
• Can use native Java lambdas if run on JVM 8.
Expressivity
• new Foo() → foo()
• foo.bar(); → foo.bar()
• Arrays.asList("foo", "bar") → listOf("foo", "bar")
Collections operations
• Lot of functional-alike operations and possibilities.
• You don’t need to write loops anymore.
• Loops are not prohibited.
• We can have Streams on Java 6.
Lambdas
strings
.filter( { it.count { it in "aeiou" } >= 3 } )
.filterNot { it.contains("ab|cd|pq|xy".toRegex()) }
.filter { s -> s.contains("([a-z])1".toRegex()) }
.size.toString()
Java Beans, POJOs and so on
• Write fields
• Write constructors
• Write getters and setters
• Write equals() and hashCode()
• …
Properties
• var age: Int = 0
• Can be accessed as a field from Kotlin.
• Getters and setters are generated automatically for Java.
• If Java code has getters and setters, it can be accessed as property from
Kotlin
• Can be computed and even lazy
Data classes
• data class User(var name: String, var age: Int)
• Compiler generates getters and setters for Java interop
• Compiler generates equals() and hashCode()
• Compiler generates copy() method — flexible clone() replacement
Data classes
• data class User(val name: String, val age: Int)
• 5 times less LOC.
• No need to maintain methods consistency.
• No need to write builders and/or numerous constructors.
• Less tests to be written.
Data classes
• Model and ViewModel conversion to Kotlin
• Made automatically
• Was: 1750 LOC in 23 files
• Now: 800 LOC
• And lot of tests are now redundant!
Extension methods
• Usual Java project has 5-10 *Utils classes.
• Reasons:
• Some core/library classes are final
• Sometimes you don’t need inheritance
• Even standard routines are often wrapped with utility classes
• Collections.sort(list)
Extension methods
• You can define extension method
• fun List.sort()
• Effectively it’ll have the same access policies as your static methods in
*Utils
• But it can be called directly on instance!
• fun List.sort() = Collections.sort(this)
• someList.sort()
Extension methods
• You can handle even null instances:
fun String?.toast(context: Context) {
if (this != null) Toast.makeToast(context,
this, Toast.LENGTH_LONG).show()
}
String interpolation
• println("Hello, world!")
• println("Hello, $name!")
• println("Hello, ${name.toCamelCase()}!")
Anko
• DSL for Android
verticalLayout {
val name = editText()
button("Say Hello") {
onClick { toast("Hello, ${name.text}!") }
}
}
Anko
• DSL for Android.
• Shortcuts for widely used features (logging, intents, etc.).
• SQLite bindings.
• Easy (compared to core Android) async operations.
Useful libraries
• RxKotlin — FRP in Kotlin manner
• Spek — Unit tests (if we still need it)
• Kotlin Android extensions — built-it ButterKnife
• Kotson — Gson with Kotlin flavor
Summary
Cost of usage
Each respective use has a .class method cost of
• Java 6 anonymous class: 2
• Java 8 lambda: 1
• Java 8 lambda with Retrolambda: 6
• Java 8 method reference: 0
• Java 8 method reference with Retrolambda: 5
• Kotlin with Java Runnable expression: 3
• Kotlin with native function expression: 4
Cost of usage
• Kotlin stdlib contains ≈7K methods
• Some part of stdlib is going to be extracted and inlined compile-time
• And ProGuard strips unused methods just perfect
Build and tools
• Ant tasks, Maven and Gradle plugins
• Console compiler and REPL
• IntelliJ IDEA — out of the box
• Android Studio, other Jetbrains IDEs — as plugin
• Eclipse — plugin
Build and tools
• Can be compiled to run on JVM.
• Can be run using Jack (Java Android Compiler Kit)
• Can be compiled to JS.
• Can be used everywhere where Java is used.
Kotlin pros and cons
• It’s short and easy.
• It has zero-cost Java
interoperability.
• You’re not obliged to rewrite all
your code in Kotlin.
• You can apply modern approaches
(like FRP) without bloating your
code.
• And you could always go back to
Java (but you won’t).
• Longer compile time.
• Heavy resources usage.
• Some overhead caused by stdlib
included in dex file.
• Sometimes errors are cryptic.
• There are some bugs and issues in
language and tools.
• Community is not so huge as Java
one.
Useful Resources
Books
• Kotlin for Android Developers.
• The first (and only) book about Kotlin
• Regular updates with new language
features
• https://leanpub.com/kotlin-for-android-
developers
Books
• Kotlin in Action.
• A book by language authors
• WIP, 8/14 chapters are ready, available
for early access
• https://www.manning.com/books/kotlin-
in-action
Links
• https://kotlinlang.org — official site
• http://blog.jetbrains.com/kotlin/ — Jetbrains blog
• http://kotlinlang.slack.com/ + http://kotlinslackin.herokuapp.com/ —
community Slack channel
• https://www.reddit.com/r/Kotlin/ — subreddit
• https://github.com/JetBrains/kotlin — it’s open, yeah!
• https://kotlinlang.org/docs/tutorials/koans.html — simple tasks to get familiar
with language.
• http://try.kotlinlang.org — TRY IT, NOW!
THANK YOU
Oleg Godovykh
Software Engineer
oleg.godovykh@eastbanctech.com
202-295-3000
http://eastbanctech.com

More Related Content

PPTX
Kotlin presentation
PPTX
Intro to kotlin
PPSX
Kotlin Language powerpoint show file
PDF
Kotlin for Android Development
PPT
The Kotlin Programming Language
PPTX
Kotlin Basics & Introduction to Jetpack Compose.pptx
PDF
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Kotlin presentation
Intro to kotlin
Kotlin Language powerpoint show file
Kotlin for Android Development
The Kotlin Programming Language
Kotlin Basics & Introduction to Jetpack Compose.pptx
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017

What's hot (20)

PDF
Introduction to kotlin
PDF
A quick and fast intro to Kotlin
PPTX
Introduction to Kotlin
PDF
TypeScript
PDF
Swift Programming Language
PPT
Java features
PDF
Introduction to kotlin coroutines
PPT
The Evolution of Java
PPTX
Android Services
PPT
Spring Boot in Action
PPTX
Introduction to iOS Apps Development
PPTX
Introduction to angular with a simple but complete project
PPTX
Angular 14.pptx
PDF
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
PDF
Introduction to the Dart language
PPTX
Servlets
PPTX
Core java complete ppt(note)
PDF
Spring boot
PDF
Hibernate Presentation
PPTX
The Javascript Ecosystem
Introduction to kotlin
A quick and fast intro to Kotlin
Introduction to Kotlin
TypeScript
Swift Programming Language
Java features
Introduction to kotlin coroutines
The Evolution of Java
Android Services
Spring Boot in Action
Introduction to iOS Apps Development
Introduction to angular with a simple but complete project
Angular 14.pptx
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Introduction to the Dart language
Servlets
Core java complete ppt(note)
Spring boot
Hibernate Presentation
The Javascript Ecosystem
Ad

Viewers also liked (6)

PDF
20111002 csseminar kotlin
PDF
Меньше кода — больше сути. Внедрение Kotlin для разработки под Android. Илья...
PDF
Session 3 - Object oriented programming with Objective-C (part 1)
PDF
Swift and Kotlin Presentation
PPTX
Architecture iOS et Android
PDF
Session 1 - Introduction to iOS 7 and SDK
20111002 csseminar kotlin
Меньше кода — больше сути. Внедрение Kotlin для разработки под Android. Илья...
Session 3 - Object oriented programming with Objective-C (part 1)
Swift and Kotlin Presentation
Architecture iOS et Android
Session 1 - Introduction to iOS 7 and SDK
Ad

Similar to Introduction to Kotlin Language and its application to Android platform (20)

PPTX
Kotlin – the future of android
PDF
Kotlin what_you_need_to_know-converted event 4 with nigerians
PDF
Little Helpers for Android Development with Kotlin
PDF
Kotlin: A pragmatic language by JetBrains
PDF
Kotlin, smarter development for the jvm
PPTX
Why kotlininandroid
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
PDF
9054799 dzone-refcard267-kotlin
PDF
Kotlin for Android Developers - 1
PDF
Lightning talk: Kotlin
PDF
Is this Swift for Android? A short introduction to the Kotlin language
PDF
Kotlin Introduction with Android applications
PPTX
Kotlin - A Programming Language
PDF
A short introduction to the Kotlin language for Java developers
PDF
Summer of Tech 2017 - Kotlin/Android bootcamp
PDF
Why Kotlin is your next language?
PPTX
PPTX
Intro to kotlin 2018
PDF
What’s new in Kotlin?
PPTX
Introduction to Kotlin for Android developers
Kotlin – the future of android
Kotlin what_you_need_to_know-converted event 4 with nigerians
Little Helpers for Android Development with Kotlin
Kotlin: A pragmatic language by JetBrains
Kotlin, smarter development for the jvm
Why kotlininandroid
Develop your next app with kotlin @ AndroidMakersFr 2017
9054799 dzone-refcard267-kotlin
Kotlin for Android Developers - 1
Lightning talk: Kotlin
Is this Swift for Android? A short introduction to the Kotlin language
Kotlin Introduction with Android applications
Kotlin - A Programming Language
A short introduction to the Kotlin language for Java developers
Summer of Tech 2017 - Kotlin/Android bootcamp
Why Kotlin is your next language?
Intro to kotlin 2018
What’s new in Kotlin?
Introduction to Kotlin for Android developers

More from EastBanc Tachnologies (14)

PPTX
Unpacking .NET Core | EastBanc Technologies
PPTX
Azure and/or AWS: How to Choose the best cloud platform for your project
PPTX
Functional Programming with C#
PPTX
Getting started with azure event hubs and stream analytics services
PPTX
DevOps with Kubernetes
PPTX
Developing Cross-Platform Web Apps with ASP.NET Core1.0
PPTX
Highlights from MS build\\2016 Conference
PPTX
Estimating for Fixed Price Projects
PPTX
Async Programming with C#5: Basics and Pitfalls
PPTX
EastBanc Technologies US-Russian Collaboration and Innovation
PPTX
EastBanc Technologies SharePoint Portfolio
PDF
EastBanc Technologies Data Visualization/BI Portfolio
PDF
EastBanc Technologies Portals and CMS Portfolio
PPTX
Cross Platform Mobile Application Development Using Xamarin and C#
Unpacking .NET Core | EastBanc Technologies
Azure and/or AWS: How to Choose the best cloud platform for your project
Functional Programming with C#
Getting started with azure event hubs and stream analytics services
DevOps with Kubernetes
Developing Cross-Platform Web Apps with ASP.NET Core1.0
Highlights from MS build\\2016 Conference
Estimating for Fixed Price Projects
Async Programming with C#5: Basics and Pitfalls
EastBanc Technologies US-Russian Collaboration and Innovation
EastBanc Technologies SharePoint Portfolio
EastBanc Technologies Data Visualization/BI Portfolio
EastBanc Technologies Portals and CMS Portfolio
Cross Platform Mobile Application Development Using Xamarin and C#

Introduction to Kotlin Language and its application to Android platform

  • 1. Introduction to Kotlin language & its application to Android platform
  • 3. What is Kotlin • Kotlin is a new programming language by Jetbrains. • It runs on JVM stack. • It has ≈zero-cost Java interop. • It runs on Android, easily.
  • 4. Let’s go! • Kotlin is a new programming language by Jetbrains. • It runs on JVM stack. • It has ≈zero-cost Java interop. • It runs on Android, easily.
  • 5. Hello, world! fun main(args: Array<String>) { println("Hello, world!") }
  • 6. Hello, world! fun main(args: Array<String>) = println("Hello, world!")
  • 7. Hello, world! fun main(args: Array<String>) = args.joinToString(postfix = "!") .forEach { print(it) } > kotlin HelloKt Hello world
  • 8. Why Kotlin? • Concise — write less boilerplate. • Interoperable — write alongside your Java code. • Multi-paradigm — you can write functional-alike code. • Promising — developed by developers for developers. • It runs on Android, easily!
  • 10. Why Kotlin? • Android runs using fork of Apache Harmony (≈Java 6). • Starting from Android API 19 (Android 4.4) it supports Java 7 features. • Android N (Nutella? 6.1?) brings support for Java 8. • But it is still Java…
  • 11. Why Kotlin? • There are lot of modern features and approaches that are unavailable even in Java 8. • Typical Java code is bloated, has a lot of boilerplate. • Kotlin is much more expressive than Java.
  • 12. Why Kotlin? final Config config = playlist.getConfig(); if (config != null && config.getUrls() != null) { for (final Url url : config.getUrls()) { if (url.getFormat().equals("txt")) { this.url = url; } } }
  • 13. Why Kotlin? playlist.config?.urls ?.firstOrNull { it.format == "txt" } ?.let { this.url = it.url }
  • 15. Null safety • You won’t see NPE anymore (unless you want) • In pure Kotlin, you can have something non-null: • var foo: String = "foo" • Or nullable • var bar: String? = "bar" • Then: • foo = null → compilation error • bar = null → OK
  • 16. Null safety • var foo: String = "foo" • var bar: String? = "bar" • foo.length → 3 • bar.length → ???
  • 17. Null safety • var foo: String = "foo" • var bar: String? = "bar" • foo.length → 3 • bar.length → compilation error • Call is null-unsafe, there are two methods to fix it: • bar?.length → 3 (or null if bar == null) • bar!!.length → 3 (or NPE if bar == null)
  • 18. Null safety • var foo: String = "foo" • var bar: String? = "bar" • if (bar != null) { • // bar is effectively not null, it can be treated as String, not String? • bar.length → 3 • }
  • 19. Null safety • Kotlin understands lot of Java annotations for null-safety (JSR-308, Guava, Android, Jetbrains, etc.) • If nothing is specified, you can treat Java object as Nullable
  • 20. Null safety • Kotlin understands lot of Java annotations for null-safety (JSR-308, Guava, Android, Jetbrains, etc.) • If nothing is specified, you can treat Java object as Nullable • Or NotNull! • It’s up to you, and you should take care of proper handling nulls.
  • 21. Type inference • var bar: CharSequence? = "bar" • if (bar != null && bar is String) { • // bar can be treated as String without implicit conversion • bar.length → 3 • }
  • 22. Type inference • fun List.reversed() = Collections.reverse(list) • Return type List is inferred automatically • //effectively fun List.reversed() : List = Collections.reverse(list)
  • 23. Lambdas • Kotlin has it • And it helps a lot • Works fine for SAM
  • 24. Lambdas strings .filter( { it.count { it in "aeiou" } >= 3 } ) .filterNot { it.contains("ab|cd|pq|xy".toRegex()) } .filter { s -> s.contains("([a-z])1".toRegex()) } .size.toString()
  • 25. Lambdas • Can be in-lined. • Can use anonymous class if run on JVM 6. • Can use native Java lambdas if run on JVM 8.
  • 26. Expressivity • new Foo() → foo() • foo.bar(); → foo.bar() • Arrays.asList("foo", "bar") → listOf("foo", "bar")
  • 27. Collections operations • Lot of functional-alike operations and possibilities. • You don’t need to write loops anymore. • Loops are not prohibited. • We can have Streams on Java 6.
  • 28. Lambdas strings .filter( { it.count { it in "aeiou" } >= 3 } ) .filterNot { it.contains("ab|cd|pq|xy".toRegex()) } .filter { s -> s.contains("([a-z])1".toRegex()) } .size.toString()
  • 29. Java Beans, POJOs and so on • Write fields • Write constructors • Write getters and setters • Write equals() and hashCode() • …
  • 30. Properties • var age: Int = 0 • Can be accessed as a field from Kotlin. • Getters and setters are generated automatically for Java. • If Java code has getters and setters, it can be accessed as property from Kotlin • Can be computed and even lazy
  • 31. Data classes • data class User(var name: String, var age: Int) • Compiler generates getters and setters for Java interop • Compiler generates equals() and hashCode() • Compiler generates copy() method — flexible clone() replacement
  • 32. Data classes • data class User(val name: String, val age: Int) • 5 times less LOC. • No need to maintain methods consistency. • No need to write builders and/or numerous constructors. • Less tests to be written.
  • 33. Data classes • Model and ViewModel conversion to Kotlin • Made automatically • Was: 1750 LOC in 23 files • Now: 800 LOC • And lot of tests are now redundant!
  • 34. Extension methods • Usual Java project has 5-10 *Utils classes. • Reasons: • Some core/library classes are final • Sometimes you don’t need inheritance • Even standard routines are often wrapped with utility classes • Collections.sort(list)
  • 35. Extension methods • You can define extension method • fun List.sort() • Effectively it’ll have the same access policies as your static methods in *Utils • But it can be called directly on instance! • fun List.sort() = Collections.sort(this) • someList.sort()
  • 36. Extension methods • You can handle even null instances: fun String?.toast(context: Context) { if (this != null) Toast.makeToast(context, this, Toast.LENGTH_LONG).show() }
  • 37. String interpolation • println("Hello, world!") • println("Hello, $name!") • println("Hello, ${name.toCamelCase()}!")
  • 38. Anko • DSL for Android verticalLayout { val name = editText() button("Say Hello") { onClick { toast("Hello, ${name.text}!") } } }
  • 39. Anko • DSL for Android. • Shortcuts for widely used features (logging, intents, etc.). • SQLite bindings. • Easy (compared to core Android) async operations.
  • 40. Useful libraries • RxKotlin — FRP in Kotlin manner • Spek — Unit tests (if we still need it) • Kotlin Android extensions — built-it ButterKnife • Kotson — Gson with Kotlin flavor
  • 42. Cost of usage Each respective use has a .class method cost of • Java 6 anonymous class: 2 • Java 8 lambda: 1 • Java 8 lambda with Retrolambda: 6 • Java 8 method reference: 0 • Java 8 method reference with Retrolambda: 5 • Kotlin with Java Runnable expression: 3 • Kotlin with native function expression: 4
  • 43. Cost of usage • Kotlin stdlib contains ≈7K methods • Some part of stdlib is going to be extracted and inlined compile-time • And ProGuard strips unused methods just perfect
  • 44. Build and tools • Ant tasks, Maven and Gradle plugins • Console compiler and REPL • IntelliJ IDEA — out of the box • Android Studio, other Jetbrains IDEs — as plugin • Eclipse — plugin
  • 45. Build and tools • Can be compiled to run on JVM. • Can be run using Jack (Java Android Compiler Kit) • Can be compiled to JS. • Can be used everywhere where Java is used.
  • 46. Kotlin pros and cons • It’s short and easy. • It has zero-cost Java interoperability. • You’re not obliged to rewrite all your code in Kotlin. • You can apply modern approaches (like FRP) without bloating your code. • And you could always go back to Java (but you won’t). • Longer compile time. • Heavy resources usage. • Some overhead caused by stdlib included in dex file. • Sometimes errors are cryptic. • There are some bugs and issues in language and tools. • Community is not so huge as Java one.
  • 48. Books • Kotlin for Android Developers. • The first (and only) book about Kotlin • Regular updates with new language features • https://leanpub.com/kotlin-for-android- developers
  • 49. Books • Kotlin in Action. • A book by language authors • WIP, 8/14 chapters are ready, available for early access • https://www.manning.com/books/kotlin- in-action
  • 50. Links • https://kotlinlang.org — official site • http://blog.jetbrains.com/kotlin/ — Jetbrains blog • http://kotlinlang.slack.com/ + http://kotlinslackin.herokuapp.com/ — community Slack channel • https://www.reddit.com/r/Kotlin/ — subreddit • https://github.com/JetBrains/kotlin — it’s open, yeah! • https://kotlinlang.org/docs/tutorials/koans.html — simple tasks to get familiar with language. • http://try.kotlinlang.org — TRY IT, NOW!
  • 51. THANK YOU Oleg Godovykh Software Engineer [email protected] 202-295-3000 http://eastbanctech.com