Contact us
Lead Software Engineer, Android & Web
Valtech, San Diego

January 08, 2019

While the Android team here at Valtech had heard of Kotlin before and began to dabble in it, it wasn’t until we attended AnDevCon Boston 2016 that we became more familiar with it and started thinking about using it in a production project. A few weeks ago we started our first Kotlin app for a client. As with picking up any new language, there was a bit of a learning curve. If you’re new to Kotlin and are considering using it in one of your projects, here’s some things I wish I would have known that will hopefully help you

Prepare to Dig Around.

The Kotlin official documentation is amazing, and there’s a great Kotlin/Android introduction on raywenderlich.com that recently came out, but there is not much out there for specific questions you may have about working with Kotlin in Android. This can be pretty frustrating when you just want to create something that you have done hundreds of times in Java, but can’t figure out how it works in Kotlin, and the few examples you come across online don’t quiteapply to your situation. One example I can think of where this happened for me was in hooking up a RecyclerView to a custom adapter and item click listener.

 

Convert Java File to Kotlin File = Life Saver.

While trudging through a situation like the RecyclerView/custom adapter, sometimes I just bit the bullet and wrote everything in Java, then used the “Convert Java File to Kotlin File” functionality in Android Studio (under the Code menu). This is a really helpful tool to see how something could be done in Kotlin. I say could because as we’ll see, there is more than one way to write something in Kotlin.

The most time consuming part of working with Kotlin is getting used to the things that will save you time.

Kotlin is a very concise language, allowing you to achieve the same result with less code, especially boilerplate code. Because of that, I found myself writing code that seemed to be the same length as Java code, and then later slimming it down to take advantage of Kotlin’s strengths. For example, there is no more wrapping a statement in a null check:

If (someThing != null) {
someThing.doSomething();
}

Turns into:

someThing?.doSomething()

What is that question mark doing there you ask? Another cool, but initially strange thing to wrap your mind around about Kotlin is how NULL is handled. Kotlin uses “nullable” and “non-null” variable types. When a variable is created and set to null, you have to put a “?” after it, and when you access that variable later, you use the “?” after it (a “nullable” variable). The variable’s property or method won’t be called if the variable is null, which avoids a NullPointerException.

There is also a “!!” operator, which is usually referred to as the “bang bang” operator (ie someThing!!.length). It’s used when you say there’s no way the variable can be null (you guessed it, a “non-null” variable). This is one place where there can actually be a NPE in Kotlin if that variable actually is NULL. There really doesn’t seem to be much benefit in using non-null objects, at least none that I’ve come across yet. Even the Kotlin docs don’t seem to like it that much: “The third option is for NPE-lovers…Thus, if you want an NPE, you can have it, but you have to ask for it explicitly, and it does not appear out of the blue”. That’s not to say that you won’t come across them, sometimes you will have to for example if an API call returns an object marked as non-null. But if you’ve initialized an object with a value, it’s safe to use !!.

Another example of how Kotlin streamlines code, by inference:

fun sum(a: Int, b: Int): Int {
   return a + b
}

Can be rewritten as:

fun sum(a: Int, b: Int) = a + b

That three line function turned into one because the Int return type is inferred by the result of a+b.

Object expressions and declarations are something you’ll see a lot that will be good to be familiar with (https://kotlinlang.org/docs/reference/object-declarations.html). Object expressions are similar to Java’s anonymous inner classes, and object declarations are Kotlin’s singletons.

Kotlin’s Lambda expressions (https://kotlinlang.org/docs/reference/lambdas.html) are also convenient to use but can take a bit to understand. Take this example:

val sum: (Int, Int) -> Int = { x, y -> x + y }

This looks like it could get hairy, but all it’s doing is declaring a variable ‘sum’ that takes two Integers, adds them together, and returns the total as an Integer. Then you would just use sum(1, 2). Pretty cool huh? And then to slim it down even more, you could use inference to modify sum to be:

val sum = { x: Int, y: Int -> x + y }

Speaking of Lambdas, take a look at this code example of Kotlin in an Android fragment:

mViewClose.setOnClickListener { fragmentManager.popBackStack() }
mViewFacebook.setOnClickListener(settingsClickListener)
mViewTwitter.setOnClickListener(settingsClickListener)

private val settingsClickListener = { view: View ->

val settingName = (view.findViewWithTag(resources.getString(R.string.setting_name_tag)) as TextView).text

  val intent = Intent()

  intent.action = Intent.ACTION_VIEW

  when (settingName) {

      resources.getString(R.string.facebook) -> {

          intent.data = Uri.parse(resources.getString(R.string.facebook_app_link))

          openSocialLink(intent, resources.getString(R.string.facebook_site_link))

      }

      resources.getString(R.string.twitter) -> {

          intent.data = Uri.parse(resources.getString(R.string.twitter_app_link))

          openSocialLink(intent, resources.getString(R.string.twitter_site_link))

      }

      …

      else -> Toast.makeText(view.context, "clicked " + settingName, Toast.LENGTH_SHORT).show()

  }

}

You may notice that the first setOnClickListener has a statement in curly braces, while the second and third have parenthesis. The first is creating an inline function statement that acts as the OnClickListener’s action. The next two are using a reference to the val settingsClickListener. settingsClickListener is creating a Lambda expression as it’s value, but you’ll notice it’s also using a View. What’s that all about? Because we’re creating an OnClickListener which takes a View as a parameter, we declare an object named “view” of type View, which is passed into the function. We are then able to use the view object in our function.

Kotlin’s custom getters and setters are pretty slick and convenient. Let’s look at an example of a custom getter:

val hasCookies: Boolean
    get() = mCookieManager?.cookieStore.cookies.filter { it.domain == mDomain && !it.hasExpired() } .size > 0

There’s a whole lot of Kotlin going on in that statement, which at first may look confusing but is a great example of how Kotlin can condense your code (Special thanks to my teammate Brigham Toskin for providing that example!). First, we’re declaring a boolean value hasCookies. We also have a custom getter. A check is done on the cookie manager’s cookies list, and is running a filter that checks if the domain matches and the expiration date hasn’t occurred. If it finds any cookies in the list that match the criteria, then hasCookiesis set to TRUE. Why is this done as a custom getter versus just a statement? As a custom getter, anytime hasCookies is accessed, the get() is called and the current state of the cookies is checked instead of just when it was declared.

So Far So Good (for the most part)

After working with Kotlin the past few weeks, I’ve definitely had my ups and downs with it. I can definitely see the potential of how it can lead to smaller code and quicker development time. Also, Kotlin is a lot more similar to Swift, so if necessary our iOS team can jump in and follow along if they need to, and eventually vice versa. The hardest part of acclimating to it is just getting used to the syntax and conventions since it’s different from Java’s syntax and conventions. Sometimes it feels like you’re trying to read hieroglyphics because there’s so much going on in not a lot of code, with unfamiliar symbols and keywords, where Java feels like things are more spelled out. But like anything, it takes time and focus to understand it.

All in all, I am glad our team here at Valtech decided to try out Kotlin on a project. I think Kotlin has a great future in Android development, and now that we have this experience under our belt I’m confident our future Kotlin projects will be even more efficient.

Contact us

Let's reinvent the future