1. Haha, er hat „Kot“ gesagt
13.09.2017 Robin Roschlau
This is a hand-out version of the talk held on Feb 01 2018 at the Gedoplan Expertenkreis. Most of the slides contain additional info in the notes that was delivered verbally in the talk.
4. What is this „Kotlin“?
4
Kotlin is a statically typed language that targets the JVM and JavaScript.
It is a general-purpose language intended for industry use.„ “
5. What is this „Kotlin“?
5
Kotlin is a statically typed language that targets the JVM and JavaScript.
It is a general-purpose language intended for industry use.„ “
2010
6. What is this „Kotlin“?
6
Kotlin is a statically typed language that targets the JVM and JavaScript.
It is a general-purpose language intended for industry use.„ “
2010 2012
7. What is this „Kotlin“?
7
Kotlin is a statically typed language that targets the JVM and JavaScript.
It is a general-purpose language intended for industry use.„ “
2010 2012 2016
v1.0
8. What is this „Kotlin“?
8
Kotlin is a statically typed language that targets the JVM and JavaScript.
It is a general-purpose language intended for industry use.„ “
2010 2012 20172016
v1.0
9. Type system
lacking
Java interop
lacking
Really? Another JVM language?
Fixes a lot of Java‘s shortcomings (Null-Safety, Type Inference, Properties, …)
Concise syntax, easy to read and write for developers used to Java
Completely interoperable
No compromises in compilation speed or tooling support
4
10. Show me some code!
Live demo
Code here: https://github.com/roschlau/kotlin-demo-jug
Online IDE with a tour through the language: https://try.kotlinlang.org/
10
13. Interoperability
13
Everything from Java is usable from Kotlin and vice versa
Inherit in one language from a class in the other language
Use all the libraries you‘re used to
Do some things in Kotlin, others in Java
Mix and match to your heart’s content.
As long as you don’t put Java and Kotlin code in the same file, anything goes.
17. Let’s get real
17
Huge legacy JavaEE application
Kotlin configured in 2 min
0
100
200
300
400
500
600
700
800
900
1000
Random DTO Random DAO Random Util Class FieldChecks ArticleSearchParameter
Java
Kotlin
-45%
-10%
-15%
-26% -66%
LOC
18. Adoption effort
18
• Getting Projects ready
• New project: No overhead
• Existing projects: < 15 min
• Working out guidelines
• How and what to migrate
• Kotlin Code Style
• Treatment of new and possibly controversial features
(Exceptions, extension functions, operator overloading, …)
• Building developer know-how
• Up-front training: ~1
• Getting comfortable: ~1 week
19. Gotchas
19
• Functions and classes are final by default.
• Mockito 2 needed to mock final classes
• Bean proxying: All-Open plugin
• No checked Exceptions
• New policy on exception handling needed
• No official SonarQube plugin yet
• JB are working on it, no ETA
• 3rd party plugins are available
• No easy way back
• Conversion from Java to Kotlin is easy and fun. The reverse, not so much.
20. Where do I start?
• http://try.kotlinlang.org
• Auto-setup a project with IntelliJ or Android Studio
• Check out the language docs and community:
http://kotlinlang.org/docs/reference/
http://kotlinlang.org/community/
https://kotlinlang.slack.com
https://stackoverflow.com/questions/tagged/kotlin
20
22. Resources
22
Official Stuff from JetBrains
Kotlin Language Reference
http://kotlinlang.org/docs/reference/
Jetbrains Motivation for developing Kotlin
https://blog.jetbrains.com/kotlin/2011/08/why-jetbrains-needs-kotlin/
Online IDE with loads of tasks and puzzles teaching the core language features
http://try.kotlinlang.org/
Kotlin FAQ
https://kotlinlang.org/docs/reference/faq.html
Kotlin Cheatsheet
https://gist.github.com/dodyg/5823184
On the Rise of Kotlin
https://blog.heroku.com/rise-of-kotlin
Kotlin vs. Scala: Which Problems do they solve?
https://superkotlin.com/kotlin-vs-scala/
Real world field reports
Kotlin for grumpy Java developers
https://medium.com/@Pinterest_Engineering/kotlin-for-grumpy-java-developers-8e90875cb6ab
Business implications of adopting Kotlin
https://www.corda.net/2017/01/10/kotlin/
The case against Kotlin
https://medium.com/@Pinterest_Engineering/the-case-against-kotlin-2c574cb87953
Lessons learned from converting an Android App to Kotlin
https://m.signalvnoise.com/how-we-made-basecamp-3s-android-app-100-kotlin-35e4e1c0ef12
23. if (durationCode.equals(Duration.H.getCode())
|| durationCode.equals(Duration.HM.getCode())) {
durationDate.add(Calendar.HOUR_OF_DAY, 1);
} else if (durationCode.equals(Duration.D.getCode())
|| durationCode.equals(Duration.DM.getCode())) {
durationDate.add(Calendar.DAY_OF_YEAR, 1);
} else if (durationCode.equals(Duration.D3.getCode())) {
durationDate.add(Calendar.DAY_OF_YEAR, 3);
} else if (durationCode.equals(Duration.W.getCode())
|| durationCode.equals(Duration.WM.getCode())) {
durationDate.add(Calendar.WEEK_OF_YEAR, 1);
} else if (durationCode.equals(Duration.M.getCode())
|| durationCode.equals(Duration.MM.getCode())) {
durationDate.add(Calendar.MONTH, 1);
} else if (durationCode.equals(Duration.MP.getCode())) {
durationDate.add(Calendar.MONTH, 1);
} else if (durationCode.equals(Duration.Y.getCode())
|| durationCode.equals(Duration.YM.getCode())) {
durationDate.add(Calendar.YEAR, 1);
} else {
throw new DurationCodeException("Duration [Code: "
+ durationCode
+ "] not found.");
}
When-Statement in practice
23
when (durationCode) {
Duration.H.code,
Duration.HM.code -> durationDate.add(Calendar.HOUR_OF_DAY, 1)
Duration.D.code,
Duration.DM.code -> durationDate.add(Calendar.DAY_OF_YEAR, 1)
Duration.D3.code -> durationDate.add(Calendar.DAY_OF_YEAR, 3)
Duration.W.code,
Duration.WM.code -> durationDate.add(Calendar.WEEK_OF_YEAR, 1)
Duration.M.code,
Duration.MM.code -> durationDate.add(Calendar.MONTH, 1)
Duration.MP.code -> durationDate.add(Calendar.MONTH, 1)
Duration.Y.code,
Duration.YM.code -> durationDate.add(Calendar.YEAR, 1)
else -> throw DurationCodeException(
"Duration [Code: $durationCode] not found.")
}
24. public void foo(String bar) {
int len = bar.length();
}
Null-Safety (Goodbye NPE, we won‘t miss you!)
24
NPE waiting to happen
Compilation Error
fun foo(bar: String) { }
fun foo(bar: String?) { }
val len = bar.length
if(bar != null) {
val len = bar.length
}
val len: Int? = bar?.length
val len: Int = bar!!.length
val bar2: String? = bar
val bar2: String = bar!!
val bar2: String = bar ?: "String was null"
25. Operator Overloading
25
class RandomClass {
operator fun plus(s: String): RandomClass {…}
override fun equals(other: Any?): Boolean {…}
operator fun compareTo(other: RandomClass): Int {…}
operator fun get(i: Int): Any {…}
operator fun set(i: Int, value: Any) {…}
operator fun contains(i: Any): Boolean {…}
operator fun invoke(p: Int) {…}
}
val r1 = RandomClass()
val r2 = RandomClass()
val r2 = r1 + "Test"
if(r1 == r2) {…}
if(r1 > r2) {…}
val a = r1[2]
r1[42] = "Test"
if("Test" in r1) {…}
r1(100)
Ever since Google officially announced its support in May 2017, Kotlin has been the talk of the Android world, but even beyond that, the language is making waves. And according to many people, this is by no means just a short-term hype, but a serious new player in the Java ecosystem that any Java developer should at least be aware of.
For all those who don't know Kotlin at all or only from hearsay, this talk provides an overview of what makes Kotlin so interesting through practical examples. It will not only give a basic introduction to the language as such, but will also shed some light on topics related to the use of Kotlin in real-world projects.
Studied at the FHDW Paderborn in cooperation with Bertelsmann / arvato
Kotlin/Android developer at MomentMap UG, using Kotlin in production for Android development since early 2016
Java developer at Deutsche Post Adress GmbH & Co. KG. Primarily using Java EE in a large web application, currently evaluating Kotlin for future development in that same application.
Conceived by JetBrains in 2010 because Java just wasn‘t cutting it anymore for them, and existing JVM alternatives were all lacking in crucial points, more on that later.
Open sourced in 2012, everybody can follow and contribute to the development of Kotlin and associated tools.
Version 1.0 was published in 2016, and is at the point of this presentation on version 1.4
In May 2017, Google officially adopted Kotlin as a adopted Kotlin as a first class language for Android development. This also came with the announcement that the development of Kotlin is being transferred to a non-profit organization, sponsored and supported by JetBrains and Google. The current Kotlin team will continue developing Kotlin, but under the new organization instead of JetBrains directly.
https://medium.freecodecamp.com/why-kotlin-is-my-next-programming-language-c25c001e26e3#.hwyu4vvl5
https://kotlin.link/articles/Kotlin-and-Ceylon.html
Comparison to other JVM-Languages borrowed and adapted from https://docs.google.com/document/d/1ReS3ep-hjxWA8kZi0YqDbEhCqTt29hG8P44aA9W0DM8/edit?hl=en&forcehl=1#heading=h.5wib5ime7f4f
Kotlin is not about the One Big Thing™ that makes it worth switching to. Rather, it just perfectly hits the sweet spot between being much better than Java, but still being familiar and seamless enough to not require much money or risk to adapt, in a way no other JVM language has managed to.
Developers: Easy pick up, more happiness through fun language, less time spent debugging NPEs and working around language restrictions, more maintainable code
Tooling: No additional costs for excellent tooling, no reduced productivity because of sub-par tools
Java Interop: No rewriting anything, just start somewhere and migrate as you feel like
All this leads to an incredibly low entry barrier and low risk for apdopting Kotlin. The biggest cost will be training developers, but even that is not much – most Java developers are up to speed with the important parts of the language in one day, and take about one week to feel comfortable in the language, during which they can already be productive again.
From experience, a lot of pure Java libraries have a steeper learning curve and are generally riskier to adopt than Kotlin!
The tooling support for Kotlin in IntelliJ is superb. You have most of the refactoring and other tools you‘re used to from Java, plus some more stuff that‘s only possible because of the stronger type system.
Setting up a new Kotlin project is just as quick as with a Java project.
Converting an existing Java project to Kotlin is as simple as adding a few things to your pom or gradle and reimporting the project, after that you‘re good to go – you can even let the Kotlin plugin do that for you.
The plugin will also convert existing Java files and even Java code snippets pasted into Kotlin files at the press of a button, which greatly helps in getting to grips with the language quickly.
The bytecode viewer and decompiler helps with understanding exactly how Kotlin translates its advanced features into bytecode.
*To be precise, this is only true for incremental builds – clean builds will take 10-15% longer, but for incremental builds (which is the more common scenario) Kotlin is at times even faster than Java.
Source: https://medium.com/keepsafe-engineering/kotlin-vs-java-compilation-speed-e6c174b39b5d#.c9ewbgxgz
The LOC count in the diagram is of some files I converted from Java to Kotlin. The steps were the same everytime: Run the automatic code converter the Kotlin plugin offers, fix any errors the resulting code has (usually due to ambiguities in the original code), and do some simple manual optimizations where verbose Java code could be written more expressively and idiomatic in Kotlin.
I could have reduced the LOC count much further by sacrificing readability, but this comparison would be meaningless if it wasn‘t usable for real projects. I made it a point to at least maintain readability so that the resulting code is as easy or even easier to read than the original code. Of course readability is subjective. Take this as „the new code is easily readable for someone who knows the basics of Kotlin, and no obscure shorthand expressions were used just for the sake of fewer LOC“.
Also, some LOC were dropped by removing empty documentation comments (as there are no separate getter/setter methods to annotate anymore in many cases), but most documentation and code comments were kept.
https://engineering.talkdesk.com/migrating-from-java-to-kotlin-the-easy-way-37b25a379d72
Starting Points für Style Guide: https://github.com/yole/kotlin-style-guide/issues/43
You can see the when-statement in action here in a real example from a project I‘ve worked on. In this case it replaces an if-else-bandwagon with a much more expressive and readable construct.
In Java, any variable (except primitives) can be null, you always have to watch your back for unexpected nulls. Nullabilty annotations somewhat try to alleviate that, making static analysis possible for IDEs, but there‘s no enforcement or standard.
In Kotlin, a variable has to be explicitly made nullable. If it is not nullable, it won‘t be null, and if it is nullable, you can‘t just use the variable‘s value without checking for null first or using one of the null-safe operators ?., !!. Or ?:.
Kotlin will work with @NotNull and @Nullable annotations to determine the appropriate types when calling Java code from Kotlin, and it will expose those annotations for Kotlin functions to Java code calling them, to make integration as seamless as possible. Because the annotations are only guidelines though, Kotlin also imposes null-checks at runtime for all not nullable parameters that are accessible from Java, to make execution fail as quickly as possible when a function was called with an illegal null parameter.
Operator Overloading is another controversial topic. Kotlin supports it in a limited way: There is a predefined set of operators that can be overloaded by adding special functions to classes, but you can‘t define completely new operators.
Some examples are listed here, there are quite some more overloadable operators. The whole list can be found here: https://kotlinlang.org/docs/reference/operator-overloading.html
Notice that == can be overridden to actually check for semantic equality instead of reference equality. If you want to force a reference equality check, you can use ===.
Be careful with this feature. Operator overloading is powerful, but if used incorrectly can make code extremely hard to understand. Kotlin restricts you by only having a fixed set of operators you can override, but you can still produce a huge mess with them if you‘re not careful.
When combined with the Anko library (also from Jetbrains), it provides a vast amount of things to take the boilerplate code out of the work of Android developers.
This code sets up a button so that it will present a confirmation dialog to the user, run a web call on a background thread when the user confirms the dialog, and give confirmation of the web call once it has completed on the UI thread again. I won‘t go into detail here, but these few lines would already need a lot more code and even a few extra classes (Dialog and AsyncTask) in their standard Java equivalent (provided that no other libraries are used, of course).
There is even more going on here that is not obvious, with the reference to `removeButton`. This is not a reference that was created earlier and assigned via a call to findViewById, this is actually a synthetic property that was automatically created from the corresponding XML layout file and can be used by just adding an import to the activity.