Skip to content

How Simpler and Shorter Code of Kotlin Has Changed the Android Development Experience?

Featured Image

At Google I/O 2017, the Android team had announced remarkable support for Kotlin, the statically typed programming language for the JVM (Java Virtual Machine).

In fact, Kotlin has already become a buzz in the Android development for years, and the number of projects developed using Kotlin is consistently increasing at Github as well. However, this language was always in a very awkward position for Android developers because it had never been supported officially. But now, the status quo has changed.

Kotlin Advantages:

Easy Learning Curve Advantage

  • A concise statically-typed programming language that is extremely easy to read and write
  • The modern and Android-compatible language that is especially designed to be type-and null-safe
  • Much simpler and shorter code than Java’s equivalent code
  • Easy debugging due to more human-readability ease
  • Playful yet much faster Android app development process

Open Source Advantage

  • Kotlin has always been an Open Source project under Apache 2 and there is a strong possibility to move Kotlin into a non-profit foundation.
  • Kotlin encourages a strong and company independent open developer ecosystem while growing the Android platform.

100% Java Compatibility Advantage

  • The level of interoperability between Java and Kotlin can be considered as one of the most powerful advantage
  • The possibilities of perfect compilation of Java and Kotlin code co-existing in the same project
  • You can use the majority of Java libraries and frameworks in Kotlin projects including advanced frameworks
  • You can use Kotlin without taking any drastic steps like converting an entire project to Kotlin.

How about IntelliJ IDEA, Eclipse or Netbeans?

  • Android Studio is built on IntelliJ IDEA, an IDE built by JetBrains—the same company behind the Kotlin language. The JetBrains team has ensured Kotlin works great with IntelliJ IDEA.
  • Starting with Android Studio 3.0, tooling support for Kotlin is bundled directly into Android Studio. Kotlin’s target to be available on multiple platforms and support for other IDEs will continue as before.

 

What Happens to Existing Languages?

Thought Kotlin has been declared official Android language, existing languages have also been empowered in the best possible way. For example:

  • Android O supports Java 8 libraries
  • C++ is intended to furnish better native experience and enhanced with expanding performance profiling tools and APK debugging tools

Kotlin Vs Java Main feature Advantage

Full Java Interoperability

  • Kotlin is 100% interoperable with Java so you can utilize all existing Android libraries including annotation processing, so data binding and Dagger work in a Kotlin application.
  • Hence, the java friendly Android developer can easily learn Kotlin and making it compatible with Android projects.

Data Classes

In the Java world, a typical data class has tons of boilerplate code that one needs to skip while finding out the real use of that class, such as the getters and setters. But in Kotlin, we can easily create a POJO (Plain Old Java Object) with getters, setters, equals(), hashCode(), toString() and copy() in a single line:
For instance, in Java, if we want to create a typical data class, we´ll need to write (or at least generate) this code:

public class UserEntity { private String userId; private String name; private String email; private String mobileNumber; public void setUserId(String userId) { this.userId = userId; } public void setName(String name) { this.name = name; } public void setEmail(String email) { this.email = email; } public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } public String getUserId() { return userId; } public String getName() { return name; } public String getEmail() { return email; } public String getMobileNumber() { return mobileNumber; }

How much code is this on Kotlin? Just this simple data class:

class UserEntity { var userId: String? = null var name: String? = null var email: String? = null var mobileNumber: String? = null }

Null safety

When we develop the application using Java, most of our code is defensive. We need to keep checking continuously if something is null before we use it. Otherwise we may find unexpected NullPointerException. Kotlin, as many other languages, is null safe because we need to explicitly specify if an object can be null by using the safe call operator.

We can do things like this:

var a: String = “abc” a = null // compilation errorvar b: String? = “abc” b = null // ok

Checking for null in conditions:

if (b != null && b.length > 0) { print(“String of length ${b.length}”) } else { print(“Empty string”) }

Safe Calls with Kotlin

b?.length

Extension functions

We can add new functions to any class. It´s a much more readable substitute to the typical utility classes we all have in our projects. We could, for instance, add a new method to fragments to show a toast:
fun Fragment.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(getActivity(), message, duration).show() }

We can do things like this with Kotlin:

fragment.toast(“Hello world!”)

Functional support (Lambdas)

What if instead of having to write the creation of a new listener every time we need to declare what a click should do, we could just define what we want to do? We can indeed. This (and many more interesting things) is what we get thanks to lambda usage:

view.setOnClickListener { toast(“Hello world!”) }

As a part of our exploration about how Kotlin actually works with the real world application, below are the Kotlin specimen codes we have created for our Hello World News application. The objective is to fetch data from server to mobile device and getting it displayed to UI in the desired format using Kotlin. The specimen codes are described in three different stages:

  • Code for fetching the list of data to mobile device from server
  • Code for displaying that data to User Interface
  • Code for data rendering using Recycler Adapter

 

Fetching the list of data to mobile device from server

// Get the list of data from server private fun getNewsList() { //Create retrofit Service var mNewsService: NewsService = ApiProduction(this).provideService(NewsService::class.java) //List of source: https://newsapi.org/sources //List of sort by option: https://newsapi.org/#apiArticles var apiCall: Observable<NewsListResponse> = mNewsService.getNewsApi(“techcrunch”, “top”, getString(R.string.new_api_key) //Test API Key ) RxAPICallHelper().call(apiCall, object : RxAPICallback<NewsListResponse> { override fun onSuccess(newsItems: NewsListResponse) { //status= “error” in case of error if (newsItems.getStatus().equals(“ok”)) { setNewsData(newsItems) } } override fun onFailed(throwable: Throwable) { } }) }

Displaying that data to User Interface

// Update data on UI private fun setNewsData(newsItems: NewsListResponse) { recyclerNews.layoutManager = LinearLayoutManager(this) val newsRecyclerAdapter: NewsRecyclerAdapter = NewsRecyclerAdapter() newsRecyclerAdapter.setData(newsItems.getArticles() as ArrayList<NewsListResponse.Article>) recyclerNews.adapter = newsRecyclerAdapter newsRecyclerAdapter.setOnItemClick(object : NewsRecyclerAdapter.MyAdapterListener { override fun onItemViewClick(mUrl:String,position: Int) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse( mUrl))) } }) }

For data rendering using Recycler Adapter

// How to render data using Recycler Adapter

class NewsRecyclerAdapter : RecyclerView.Adapter<NewsRecyclerAdapter.TaskViewHolder>() { lateinit var tasks: ArrayList<NewsListResponse.Article> lateinit var mItemClickListener: MyAdapterListener override fun onCreateViewHolder(parent: android.view.ViewGroup, type: Int): TaskViewHolder { return TaskViewHolder(parent) } fun setData(tasks: ArrayList<NewsListResponse.Article>) { this.tasks = tasks notifyDataSetChanged() } fun addTodo(todoTask: NewsListResponse.Article) { this.tasks.add(todoTask) notifyItemChanged(tasks.size) } override fun onBindViewHolder(viewHolder: NewsRecyclerAdapter.TaskViewHolder, position: Int) { viewHolder.bind(tasks[position], position) } override fun getItemCount(): Int = tasks.size inner class TaskViewHolder(parent: android.view.ViewGroup) : RecyclerView.ViewHolder(android.view.LayoutInflater.from(parent.context). inflate(R.layout.list_item_news, parent, false)) { fun bind(task: NewsListResponse.Article, position: Int): Unit = with(itemView) { tvListItemAuthor.text=task.author tvListItemDateTime.text=task.publishedAt tvListItemTitle.text=task.title itemView.setOnClickListener({ task.url?.let { mUrl -> mItemClickListener.onItemViewClick(mUrl,position) } }) Glide.with(itemView.context) .load(task.urlToImage) .into(ivListItem) var df: DateFormat = SimpleDateFormat(“yyyy-MM-dd’T’HH:mm:ss”, Locale.getDefault()) val d = df.parse(task.publishedAt) df = SimpleDateFormat(“dd MMM,yyyy hh:mm a”, Locale.getDefault()) tvListItemDateTime.text=df.format(d) } } fun setOnItemClick(itemClickListener: MyAdapterListener): Unit { this.mItemClickListener = itemClickListener } interface MyAdapterListener { fun onItemViewClick(webUrl:String,position: Int)

Conclusion

Be it about optimum usage of Kotlin’s separate interfaces for read-only and mutable collections, primary constructors, string templates and smart casts or fetching the advantage of type inference for variable and property types I have found many good reasons to opt for Kotlin. I believe, this developer friendly language has a potential to furnish the programmers with the ease of simplicity and fun.

Related Insights