Author: Oleg Godovykh, eastbanctech.com
Kotlin is a new programming language built by Jetbrains and is a new member of JVM family. As opposed to typical reason to introduce some new language, Kotlin main goal isn't to create new paradigm or fill a new niche, but to make routine tasks much easier and safer. Kotlin gains popularity across Android developer community, and in this presentation it is shown how Kotlin usage can dramatically simplify typical mobile app development.
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.
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;
}
}
}
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)
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()
}
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!