SlideShare ist ein Scribd-Unternehmen logo
1 von 51
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

Weitere ähnliche Inhalte

Was ist angesagt?

Kotlin vs Java | Edureka
Kotlin vs Java | EdurekaKotlin vs Java | Edureka
Kotlin vs Java | EdurekaEdureka!
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
Kotlin Basics & Introduction to Jetpack Compose.pptx
Kotlin Basics & Introduction to Jetpack Compose.pptxKotlin Basics & Introduction to Jetpack Compose.pptx
Kotlin Basics & Introduction to Jetpack Compose.pptxtakshilkunadia
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Atif AbbAsi
 
Jetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidJetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidNelson Glauber Leal
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
 
Introduction to SOLID Principles
Introduction to SOLID PrinciplesIntroduction to SOLID Principles
Introduction to SOLID PrinciplesGanesh Samarthyam
 
Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Simplilearn
 
Jetpack Compose.pptx
Jetpack Compose.pptxJetpack Compose.pptx
Jetpack Compose.pptxGDSCVJTI
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core javamahir jain
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Web Test Automation with Selenium
Web Test Automation with SeleniumWeb Test Automation with Selenium
Web Test Automation with Seleniumvivek_prahlad
 
Jetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UIJetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UIGilang Ramadhan
 
Jetpack Compose beginner.pdf
Jetpack Compose beginner.pdfJetpack Compose beginner.pdf
Jetpack Compose beginner.pdfAayushmaAgrawal
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility PrincipleEyal Golan
 

Was ist angesagt? (20)

Kotlin vs Java | Edureka
Kotlin vs Java | EdurekaKotlin vs Java | Edureka
Kotlin vs Java | Edureka
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Kotlin Basics & Introduction to Jetpack Compose.pptx
Kotlin Basics & Introduction to Jetpack Compose.pptxKotlin Basics & Introduction to Jetpack Compose.pptx
Kotlin Basics & Introduction to Jetpack Compose.pptx
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
 
Jetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidJetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on Android
 
Ionic Framework
Ionic FrameworkIonic Framework
Ionic Framework
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Introduction to SOLID Principles
Introduction to SOLID PrinciplesIntroduction to SOLID Principles
Introduction to SOLID Principles
 
Android with kotlin course
Android with kotlin courseAndroid with kotlin course
Android with kotlin course
 
Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022
 
Java vs kotlin
Java vs kotlin Java vs kotlin
Java vs kotlin
 
Jetpack Compose.pptx
Jetpack Compose.pptxJetpack Compose.pptx
Jetpack Compose.pptx
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Web Test Automation with Selenium
Web Test Automation with SeleniumWeb Test Automation with Selenium
Web Test Automation with Selenium
 
Jetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UIJetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UI
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Jetpack Compose beginner.pdf
Jetpack Compose beginner.pdfJetpack Compose beginner.pdf
Jetpack Compose beginner.pdf
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 

Andere mochten auch

Меньше кода — больше сути. Внедрение Kotlin для разработки под Android. Илья...
 Меньше кода — больше сути. Внедрение Kotlin для разработки под Android. Илья... Меньше кода — больше сути. Внедрение Kotlin для разработки под Android. Илья...
Меньше кода — больше сути. Внедрение Kotlin для разработки под Android. Илья...Yandex
 
Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)Vu Tran Lam
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin PresentationAndrzej Sitek
 
Architecture iOS et Android
Architecture iOS et AndroidArchitecture iOS et Android
Architecture iOS et AndroidHadina RIMTIC
 
Session 1 - Introduction to iOS 7 and SDK
Session 1 -  Introduction to iOS 7 and SDKSession 1 -  Introduction to iOS 7 and SDK
Session 1 - Introduction to iOS 7 and SDKVu Tran Lam
 

Andere mochten auch (6)

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

Ähnlich wie Introduction to Kotlin Language and its application to Android platform

Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Mohamed Nabil, MSc.
 
Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinayViplav Jain
 
Down the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandDown the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandCharles Nutter
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developersMohamed Wael
 
Introduction to Kotlin for Java developer
Introduction to Kotlin for Java developerIntroduction to Kotlin for Java developer
Introduction to Kotlin for Java developerShuhei Shogen
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaCharles Nutter
 
The Future of Node - @rvagg - NodeConf Christchurch 2015
The Future of Node - @rvagg - NodeConf Christchurch 2015The Future of Node - @rvagg - NodeConf Christchurch 2015
The Future of Node - @rvagg - NodeConf Christchurch 2015rvagg
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Mario Camou Riveroll
 
C101 – Intro to Programming with C
C101 – Intro to Programming with CC101 – Intro to Programming with C
C101 – Intro to Programming with Cgpsoft_sk
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageAzilen Technologies Pvt. Ltd.
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at TwitterAlex Payne
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scalatod esking
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building BlocksCate Huston
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Ryan Cuprak
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Henry S
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?hawkowl
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developersAndrei Rinea
 

Ähnlich wie Introduction to Kotlin Language and its application to Android platform (20)

Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1
 
Kotlin from-scratch
Kotlin from-scratchKotlin from-scratch
Kotlin from-scratch
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinay
 
Down the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandDown the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM Wonderland
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Introduction to Kotlin for Java developer
Introduction to Kotlin for Java developerIntroduction to Kotlin for Java developer
Introduction to Kotlin for Java developer
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
The Future of Node - @rvagg - NodeConf Christchurch 2015
The Future of Node - @rvagg - NodeConf Christchurch 2015The Future of Node - @rvagg - NodeConf Christchurch 2015
The Future of Node - @rvagg - NodeConf Christchurch 2015
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?
 
C101 – Intro to Programming with C
C101 – Intro to Programming with CC101 – Intro to Programming with C
C101 – Intro to Programming with C
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scala
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building Blocks
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developers
 

Mehr von EastBanc Tachnologies

Unpacking .NET Core | EastBanc Technologies
Unpacking .NET Core | EastBanc TechnologiesUnpacking .NET Core | EastBanc Technologies
Unpacking .NET Core | EastBanc TechnologiesEastBanc Tachnologies
 
Azure and/or AWS: How to Choose the best cloud platform for your project
Azure and/or AWS: How to Choose the best cloud platform for your projectAzure and/or AWS: How to Choose the best cloud platform for your project
Azure and/or AWS: How to Choose the best cloud platform for your projectEastBanc Tachnologies
 
Getting started with azure event hubs and stream analytics services
Getting started with azure event hubs and stream analytics servicesGetting started with azure event hubs and stream analytics services
Getting started with azure event hubs and stream analytics servicesEastBanc Tachnologies
 
Developing Cross-Platform Web Apps with ASP.NET Core1.0
Developing Cross-Platform Web Apps with ASP.NET Core1.0Developing Cross-Platform Web Apps with ASP.NET Core1.0
Developing Cross-Platform Web Apps with ASP.NET Core1.0EastBanc Tachnologies
 
Highlights from MS build\\2016 Conference
Highlights from MS build\\2016 ConferenceHighlights from MS build\\2016 Conference
Highlights from MS build\\2016 ConferenceEastBanc Tachnologies
 
Async Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and PitfallsAsync Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and PitfallsEastBanc Tachnologies
 
EastBanc Technologies US-Russian Collaboration and Innovation
EastBanc Technologies US-Russian Collaboration and InnovationEastBanc Technologies US-Russian Collaboration and Innovation
EastBanc Technologies US-Russian Collaboration and InnovationEastBanc Tachnologies
 
EastBanc Technologies SharePoint Portfolio
EastBanc Technologies SharePoint PortfolioEastBanc Technologies SharePoint Portfolio
EastBanc Technologies SharePoint PortfolioEastBanc Tachnologies
 
EastBanc Technologies Data Visualization/BI Portfolio
EastBanc Technologies Data Visualization/BI PortfolioEastBanc Technologies Data Visualization/BI Portfolio
EastBanc Technologies Data Visualization/BI PortfolioEastBanc Tachnologies
 
EastBanc Technologies Portals and CMS Portfolio
EastBanc Technologies Portals and CMS PortfolioEastBanc Technologies Portals and CMS Portfolio
EastBanc Technologies Portals and CMS PortfolioEastBanc Tachnologies
 
Cross Platform Mobile Application Development Using Xamarin and C#
Cross Platform Mobile Application Development Using Xamarin and C#Cross Platform Mobile Application Development Using Xamarin and C#
Cross Platform Mobile Application Development Using Xamarin and C#EastBanc Tachnologies
 

Mehr von EastBanc Tachnologies (14)

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

Kürzlich hochgeladen

Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesChandrakantDivate1
 
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...nishasame66
 
Mobile App Penetration Testing Bsides312
Mobile App Penetration Testing Bsides312Mobile App Penetration Testing Bsides312
Mobile App Penetration Testing Bsides312wphillips114
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsChandrakantDivate1
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsChandrakantDivate1
 

Kürzlich hochgeladen (6)

Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & Examples
 
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
 
Mobile App Penetration Testing Bsides312
Mobile App Penetration Testing Bsides312Mobile App Penetration Testing Bsides312
Mobile App Penetration Testing Bsides312
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s Tools
 
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and Layouts
 

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 oleg.godovykh@eastbanctech.com 202-295-3000 http://eastbanctech.com