Latest posts by Hussain Fakhruddin (see all)
- How do mobile apps help small businesses? - October 10, 2019
- Top 15 Mobile App Ideas For 2020 - October 1, 2019
- Top 15 Software Development Trends To Watch Out For In 2020 - September 18, 2019
At this year’s Google I/O, Kotlin – the statically-typed language from JetBrains – became an official language for android (i.e., received the ‘first-class language status’). Initially announced in 2011 and launched in early-2016 – Kotlin is now included in Android Studio 3.0, which was launched last week. In June, Kotlin ranked a perfectly respectable 43rd (on the Tiobe Language Popularity Index) – jumping up from the 80th spot in the previous month. Experts feel that, at this rate, the language can soon break into the list of top-20 languages (in June, Apple’s Swift was at 12th).
For coding for Android applications, developers need a language that is ‘understandable‘ by the Java Virtual Machine (JVM). The arrival of Kotlin has given coders an alternative to the traditionally used Java language. In what follows, we will do an objective, point-by-point Java vs Kotlin comparison – and try to find out which one has the better properties:
The learning curve
For switching over from an established language like Java to a new one like Kotlin to be a practically viable proposition, the learning curve for the latter has to be fairly simple (otherwise, the loss of skills and man-hours can be considerable). For experienced Java developers, the Kotlin language brings with it a high degree of familiarity – with things like the coding process for making new classes being nearly identical. Java and Kotlin share a number of syntaxes too, making things easier for developers. In essence, Kotlin can be viewed as an ‘improvement’ on Java, rather than being a full-blown substitute. If a coder is well-versed in Java, that skill and experience will stand him/her in good stead while starting to work with Kotlin.
The issue with NullPointerExceptions
NullPointerExceptions, also known as ‘The Billion Dollar Mistake’, are a constant source of irritation of Android app developers coding with Java. In case a null value is assigned to any of the object references (in Java, any variable can have null value), this exception is thrown. In Kotlin, this problem is kept out of the equation – thanks to its inherent null-safety feature. Unless specially marked as ‘nullable’, no variable in Kotlin code can hold a null value. Even if you make a mistake and do assign a null value, the code will fail at the time of compilation. In non-trivial pieces of code, looking for the cause(s) of NullPointerExceptions can be problematic and time-consuming. Kotlin offers an easy way out of it.
Kotlin is the ‘modern’ language
A high percentage of Android app makers worldwide work with Java 7 – simply because all the features of Java 8 are not yet available on the platform. The Android plugin has to be updated to v.3.0.0, and after that, users can play around with a limited subset of Java 8 features in the toolchain (after disabling Jack). Type annotations, lambda expressions, and method references are some of the important Java 8 features available on Android (some Java 8 language APIs are also supported). On the other hand, Kotlin captures the best points of procedural and functional programming (Java is still mostly procedural) – offering the latest tools and resources to the developers. It is easily the more modern, lightweight and well-rounded language, and is, hence, widely regarded as an enhancement over Java.
The seamless interoperability between Java and Kotlin makes the task of Kotlin beginners that much easier. Within the same project, both Java and Kotlin files can be used – without the risk of any error being thrown. Kotlin libraries can be used in primarily Java projects easily (the reverse is also true). The fact that Java and Kotlin classes can reside simultaneously in the project does away with the need for full project conversion (to Kotlin), or having to start a project from scratch. First-time users of Kotlin can try coding with the new language on a specific part of a project – while keeping the legacy Java codes intact. Later, they can proceed to migrating the Java files to Kotlin (the migration should be one file at a time). There can be the occasional code in Kotlin that is difficult to decipher, although the inherent intuitiveness of the language should give developers some idea in such cases too. Interoperability with Java (extending to advanced Java libraries) is a key factor behind the rising adoption rate of Kotlin.
Note: Scala and Clojure are two other languages that are used to build Android apps. While both are JVM-friendly, none of these two have managed to become very popular (although they were launched before Kotlin).
By virtue of being one of the oldest open-source programming languages ever, Java has a huge, and highly active, developer community across the globe. Regular updates are available (although they might not be immediately available for Android), and developers can get a lot of codes and references online. The online support for Kotlin cannot come close to matching that for Java, although the newer language is growing at a rapid clip. At last count, there were 2000+ Kotlin-based projects in Github – marking the remarkable rate at which Kotlin is growing. Even so, the probability of hitting a roadblock while coding for an app, with no support available, can be slightly higher for Kotlin-users. In the Java community, help is always available at hand.
For carrying out the same function (say, creating a floating action button), the volume of coding required in Java is considerably more than in Kotlin. In general, Kotlin has been designed as a significantly more compact language than Java. With the help of the Kotlin Android Extensions, references can be quickly imported inside Activity files (within Views) – and then, that View can be used in the code as part of the Activity. This, in turn, means that developers do not have re-write the ‘findViewByld’ method for each case. Java does not have this feature – and hence, the amount of boilerplate code included in Java programming is a lot higher than that involved in Kotlin. All that the developer has to do before using the Kotlin extensions is add an additional plugin in the build.gradle file (inside the module). Unlike Java, there is no need for third-party dependency injection tools in Kotlin either.
Note: For coding a simple “Hello World” program in Kotlin, no classes or main method(s) are required. Less verbosity also, of course, lowers the probability of manual coding errors as well.
Java has checked exceptions (i.e., Android developers have to catch and declare the exceptions), while Kotlin does away with them. There are many programmers who prefer having these checked exceptions – since they can make the code more robust and effective, by putting a definite emphasis on error recovery. However, in lengthy pieces of code, the many Java try/catch blocks can make things cluttered. From that standpoint, the absence of checked exceptions in this language can be viewed as an advantage. Opinions are divided in this regard – and it all boils down to what individual programmers are more comfortable working with. The overall codebase of Kotlin is more idiomatic than Java.
Increased size of .apk
Not a major point of concern for small apps – but if the Android application you are working on has a large size, this can be a factor. Professional developers have confirmed that the Kotlin Standard Library increases the average size of .apk files by 800 KB – 1 MB. In Java, there is no such increase in the runtime sizes of .apk files. In select cases, this increased file size can cause issues (end users might consider this while downloading apps that are already ‘heavy’). The relative lack of complex Kotlin examples available online is also holding the language back somewhat. Java has the edge in this context, and Kotlin has plenty of scopes for refinement.
Note: With the plugin available in Android SDK 3.0, Kotlin (Java) files can be converted to Java (Kotlin).
Complete support for Kotlin in Android Studio
The Android Studio IDE (integrated development environment) offers holistic support for the Kotlin language, ensuring that Android developers can easily make the switch from Java to the newer language. After installing and setting up the Kotlin plugin in Android Studio, configuring a new project is typically a matter of minutes – while there should not be any problems with initial readability and code compilation either. Right from code navigation and code completion, to refactoring, debugging and unit testing – Android Studio offers full support for all important activities in Kotlin. Converting complete source files written in Java to Kotlin is also a breeze. Developers, of course, have to ensure that there are no code losses and/or data corruption during such conversions. Incidentally, both Intellij (the base of Android Studio) and Kotlin have been created by JetBrains.
Implicit widening conversions and that question of stability
Java offers built-in support for implicit widening conversions with numbers. This keeps things straightforward. While coding in Kotlin though, Android developers have to go through the whole hog of performing similar conversions explicitly (implicit conversions are not supported) – every time a Byte value has to be assigned to an Int variable. In the Java framework, the smaller data types are converted to larger types under the hood – which is both quicker and simpler. Add to that the considerable mindshare that Java still enjoys (there is a certain feel of stability while using an old, ‘tried-and-tested’ language) – and it becomes pretty much apparent that the popularity of Java is not going to drop off drastically anytime soon.
Higher-order functions and data classes
With the arrival of Java 8, support was finally extended for lambdas. However, as already mentioned earlier, all its features are not available to Android developers – who generally have to work with Java 6 or Java 7. In Kotlin, things are a lot more developer-friendly – with variables able to store functions for use later on. Lambdas, which are created by passing functions as expressions without declaring it (implicitly or explicitly) are supported in Kotlin, along with other higher-order functions (functions taken as parameters), like callback functions. Since Java does not support these, developers have to create a new interface and implement it separately (in Kotlin, there is only a handful of parameter functions). The conciseness of Kotlin becomes apparent while handling data classes. Unlike Java, where large volumes of boilerplate code has to be written for the different classes which only contain data, Kotlin allows users to perform the same function – simply by adding a keyword (‘data’) inside the class definition. Instead of having to create new fields and constructors for data storage (in Java), all ‘getters/setters’ are auto-generated by the compiler (in Kotlin).
No extra garbage collection
A common bone of concern among many Android app developers working with Java is the extra garbage collection – which often renders the code less than optimally efficient. The problem gets particularly pronounced in instances of lengthy programs. Kotlin comes across as a better alternative – removing such problematic garbage collection (the garbage collector, of course, depends on the runtime, and not on the underlying programming language per se). What’s more – there are several XML-related pain points in Java, which can be removed in Kotlin – thanks to the Kotlin source file named Anko Library.
Note: The extension functions of Kotlin help in creating clean, easy-to-understand APIs.
13. First-class delegation in Kotlin
Also known as ‘implicit delegation’, this is a unique feature that gives Kotlin a further boost. Operations can be delegated by received objects to other ‘delegate’ objects (helper objects) – which means that the language itself follows the ‘delegation over inheritance’ rule of thumb. Code duplication (say, on the setters and getters of different properties) can be avoided with the delegated ‘properties’ of Kotlin – while multiple inheritance is also made possible. In addition, Kotlin also renders the task of type-checking before casting objects (in certain cases) unnecessary. The smart casts of Kotlin ensure that objects that are already checked with the ‘is’ operator do not have to be casted again inside statements. In other words, the redundancy in casting gets removed.
14. Speed of compilation
Java is still the ‘faster’ language – with tests revealing that it has, on average, ~13% faster compilation speeds (with Gradle) than Kotlin (14.2 seconds vs 16.6 seconds). However, this difference of speeds is only for full bields. Since mobile app developers generally keep compiling codes after making certain changes – the more important parameter over here is the incremental speed of compiling (version 1.0.2 of Kotlin has incremental building). Now, the speed advantage of Java more or less disappears, with Kotlin either being at par, or even just a bit faster, for partial builds with incremental compilation. Summing up, Java performs ‘clean builds’ more quickly – but the two languages are similar (Kotlin might even have a slight advantage) in case of partial builds.
15. The advantage of having ‘coroutines’
Android is a single-thread platform. In case this main thread is interrupted in any way (say, due to an intensive network I/O operation) – the UI of the app is likely to freeze, till the operation is completed. To avoid this problem, Java makes it necessary for developers to create background thread(s). This has a potentially serious downside – in the form of problems/confusions while managing multiple threads. Kotlin offers the smarter solution through coroutines. Executions can be suspended while performing the intensive operation, and resumed later – and the main thread does not get blocked at any point (the execution is generally restarted on a separate thread). Putting it in another way, Kotlin allows the creation of non-interrupting asynchronous codes, with coroutines being an important utility feature for developers.
Already, many Java libraries have started to provide Kotlin extensions (RxKotlin is a classic example). This, expectedly, is pulling up the usability of Kotlin. The language is further boosted by the built-in support for all important Java libraries and frameworks. It is still advisable for newbie Android developers to learn Java first, and then attempt the switch to Kotlin (type aliases and immutability are two more USPs). The former scores over Kotlin on a couple of factors (the huge community support is perhaps the biggest) – but Kotlin is closing in, and it does offer a fair few advantages over Java.
Which programming language do you prefer? Let us know in comments!