DEV Community


Posted on

Kotlin - First Impression

Cross-post from Trent's Dev Blog.

It's been 3 weeks since I started a new project written entirely in Kotlin. These 3 weeks were great. I could enjoy functional programming from my Scala experience with strict static typing I always love. All of this, without sacrificing productivity. Great Kotlin features that I keep using are :

You can create immutable value classes with just one line of code. Java can do this too, but it's almost too verbose for Java to use it this way. It is very useful for declaring custom data types with small number of values. I mostly use it to enhance static typing of certain primitive type value sets. It is possible to include compile-time type checks for almost everything, while making code more concise and readable with less error-prone variable handling. Destructuring Declarations makes it more easy and convenient to use.

Extension Functions really make Kotlin special compared to Java. It is almost too powerful, yet I find myself using it constantly. All the methods in Android you wish the library already had - whether it's simply starting an Activity or opening a Camera with specific parameters - are in your finger tips, such that you can customize the framework(or the language) any way you want. Be careful not to include any external state(variable) in the methods though. It might unnecessarily complicate the program(it would be similar to using a singleton to store state). If you are using Extension Functions merely for syntactic sugar, I suggest you decide the scope of the method carefully.

Functions like let, apply, run, use are very valuable for keeping a clear code. They help to separate procedural code into blocks of operations performed on a variable. This is very useful, because even with Extension Functions it's impractical to hide all sequential operations to a variable in a separate function. In this aspect, apply is very interesting, in that it is designed to couple variable assignment with custom initialization. Combined with ? operator, those functions can also keep unnecessary null checks to a minimum. Use them generously. Just keep in mind to don't nest them too much. In fact, I never nest them. It would introduce unnecessary depth, along with possible it & this & return headaches.

All in all, I think Kotlin is a very satisfying language. I plan to dive more deeper into the language, and explore more techniques for writing cleaner, more manageable code. I suggest you do too. Until next time!

Top comments (0)