Kotlin vs Java for Android Development in 2023

Introduction

Welcome fellow developer! As you know, building mobile apps that work seamlessly on both Android and iOS represents an enormous opportunity. However, developers face constant tension deciding whether to maximize native platform benefits or share common code. When weighing Kotlin and Java, there are critical factors around architecture, performance, safety and developer experience to consider…

The dominance of Android and iOS is projected to continue expanding over the next decade, combining to represent 99%+ of all mobile app usage. Both platforms provide proprietary SDKs and tooling delivering tailored user experiences. But companies also want faster feature development velocity alongside potential web and backend code reuse…

Android Software Architecture

To set context, let‘s understand the core Android software stack. At the bottom sits the Linux kernel providing low-level device driver, power management and other capabilities. On top of that resides the Android Run Time (ART) which plays a similar role to the Java Virtual Machine (JVM)…

ART parses and optimizes bytecode from both Java and Kotlin into efficient native instructions targeting ARM processors powering most mobile devices today. This helps explain why choosing JVM-targeting languages facilitates aligning skills and sharing modules across other environments…

[Diagram of Android architecture layers]

Java History on Mobile

Java enjoyed early success powering Blackberry, Symbian and other mobile operating systems last decade. When Android launched in 2008, requiring Java proficiency for app development seemed a safe choice given its popularity on servers…

This helped establish Java dominance across Android. However limitations began to emerge such as null pointer exceptions, verbose syntax, lack of functional concepts and slow build times. Could a modern successor deliver significant advantages?

Kotlin Traction on Android

First unveiled publicly in 2011 by JetBrains, Kotlin aimed to compile down to efficient JVM bytecode while incorporating best practices from Scala and C#. It gained increasing traction in backend web roles for companies like Netflix and Pinterest…

When Google announced first-class Kotlin support for Android in 2017 it legitimatized usage for mobile apps. Kotlin offered a path forward preserving existing Java code investments while gradually adopting productivity and safety improvements. Several factors contributed to rapid adoption since…

Language Trends and Rankings

Per the PYPL index which analyzes Google searches for language tutorials, Kotlin has demonstrated impressive year over year growth:

[Plot PYPL percentages over time for Java vs Kotlin, showing Kotlin rising precipitously from 1.2% to 4.8% while Java fell slightly from 23% down to 21%]

The TIOBE index based on search engine results tells a similar story:

[Plot TIOBE rankings showing Kotlin rising from #60 up to #13 since 2017 while peaking at #3 in 2020. Java #1 overall but falling.]

Analyzing internal metrics released in 2021, Google reported that 80% of the top 1000 Android apps contain Kotlin code. The median app contains 9% Kotlin but the top 10 percentile have fully converted to Kotlin…

Case Studies and Wins

High profile mobile applications choosing to migrate fully from Java to Kotlin include Basecamp, Khan Academy, Flipboard, SoundCloud Go and many others…

For example, leading project management SaaS Basecamp shared that Kotlin enabled them to reduce total file count by 7.75% while lowering method count by 8.3%. The total compilation time for the Android app dropped from 115 to just 35 seconds following the conversion effort…

Architectural Patterns

The Kotlin language and associated ecosystem provide guidance around modern application architecture approaches. For example using "Clean Architecture" principles like dividing an app into domain, data and presentation layers can improve separation of concerns…

Traditional Android apps tended to have activity and fragment classes span too many responsibilities leading to inflated files. Adopting cleaner presentation and logic divisions simplifies testing and maintainability long term…

[Clean architecture diagram contrasted with bloated activity file]

Other benefits arise from leveraging Kotlin Coroutines for asynchronous operations. Building on established reactive libraries…

Sharing Code Across Platforms

Kotlin Multiplatform (MPP) opened exciting possibilities for easily reusing modules across client, server and web applications. This involves defining common data objects and interfaces once then importing everywhere…

For example, here is an extract function that can parse JSON across multiple platforms by leveraging Kotlin serialization:

expect fun <T> String.parseJson(deserializer: DeserializationStrategy<T>): T

public inline fun <reified T> String.parseJson(): T = 
    parseJson(Json { ignoreUnknownKeys = true }.decodeFromString(T::class.java)) 

The expect mechanism indicates details get implemented appropriately per platform whether JS or JVM. This avoids lock-in compared to alternatives like React Native…

Coroutines Guide

Kotlin coroutines enable writing async code based on collaborative scheduling rather than callbacks. This approach resembles async/await in JS…

Some best practices include:

  • Always scope coroutines appropriately to lifecycles to prevent leaks
  • Dispatch CPU intensive work to I/O pool threads
  • Ensure structured concurrency using supervised jobs
  • Leverage flow for reactive streams that suspend
  • Minimize concurrent coroutines to avoid thread starvation

Testing Kotlin on Android

To reliably test Kotlin application modules, JUnit 5 delivers a robust feature set including parametrized tests…

The modern mockk library offers idiomatic mocking approaches for isolating dependencies. Avoiding reflection reduces surprises:

@Test 
fun validateLogin() {

  val user = mockk<UserService>() 
  every { user.login(any(), "1234") } returns Result.Success

  loginViewModel.login(user)

  assertTrue(loginViewModel.success) 
}  

Additionally, AndroidX Test provides domain specific assertions when running instrumentation tests on emulators or devices…

The Future is Cross-Platform

Kotlin delivers tangible improvements over Java across syntax, safety and developer happiness dimensions while preserving existing code assets and skills. Android represents just one of many potential platforms from cars to TVs innovating on JVM foundations…

As Kotlin momentum compounds across startups and enterprises alike, Java will continue playing a key role where stability matters most. The future remains multi-language. But Kotlin represents the next leap forward in productivity and safety for mobile application developers.