This is not something fancy or magical about Kotlin at all, but I was asked about this multiple times in the past few months, so I think this may be something worth to share.
In my previous post Kotlin “By” Class Delegation: Favor Composition Over Inheritance I covered using
by keyword for class delegations. You can easily reuse and compose existing concrete implementations in your code. In this post I will be going over using the same
by keyword for properties and how you can use them to create reusable code and reduce awkward boilerplate code. I will also include some Android specific samples with delegated properties.
KotlinConf is the first ever conference that is all about the new favorite language Kotlin. The event is held by Jetbrains officially at Pier 27, San Fransisco. It is two day long and you can see many developers from big companies like Google, Gradle, Pivotal, Facebook giving talks or or attending events themselves. I was lucky enough that I purchased my ticket for $99 on the first day they announced the event, and four friends/coworkers of mine went together, making this event even more enjoyable.
When people ask me why Kotlin over Java, I often say because Kotlin is a better Java. You get more than half of Effective Java implemented for you. In charter 4 of the book, the author lists many items about inheritance because it is very error prone. The most well known item probably would be Item 16: Favor composition over inheritance. To implement that item, Kotlin introduces a special key work
by to help you with implementing delegation in a single line.
A week ago I was thinking of writing a small Kotlin command line tool to read some local json files. I opened IntelliJ and started a kotlin project with gradle. Everything worked just fine. I could compile and run the output jar file until I imported autovalue. Autovalue uses annotation processor to generate model objects, but IntelliJ just would not invoke annotation processing properly so the compilation failed. I did some research and finally made it to work, and I think these tricks are worth to share.
Writing custom views or view groups is quite common nowadays, but sometimes it can be really cumbersome. You have to write overloaded constructors so that they would work properly in layout editor, or you define and implement some interfaces so that you don’t have to copy and paste the same code in different subclasses. With Kotlin we can easily avoid those common pain points when writing custom views and still enjoy full interoperability with Android!
Kotlin defines a few of extension functions like
apply() in its Standard.kt file. You probably have seen some of them in various tutorials or even used them already. Sometimes you may also wonder which one to use. In this post, I will walk through those confusing functions and see if we can understand the differences.
- OLDER POSTS
- page 1 of 2