Doug Stevenson
Feb 1, 2016 · 6 min read
Image for post
Image for post

Disclaimer: I am a Google employee, but the views expressed in this article are not those of my employer.

Kotlin & Android: A Brass Tacks Experiment, Part 2

This is part 2 of a series exploring what the Kotlin® language can uniquely offer Android developers. Last time there was some detail on how to get Kotlin support added to an Android project. Now we’ll actually dive into code and see how some Kotlin language features can be used to do nifty things in an Android project.

When I first encountered Kotlin and pored over the list of language features, one thing in particular stood out to me. Kotlin has a feature called type-safe builders that lets you express object creation in a style that looks declarative. It allows a syntax that looks a lot like Gradle build files. But where Gradle and Groovy are dynamically typed, Kotlin is statically typed, so the compiler will let you know if you’re assigning values to properties that don’t make sense.

The typical examples of type-safe builders show how it’s possible to build nested data structures, like XML documents. When I think Android and XML, layouts and views quickly come to mind. If Kotlin is good at building up stuff like XML programmatically, perhaps it would do well with view hierarchies. So, that’s where I started. I figured I would try to create a sort of shorthand for building view hierarchies programmatically, which is code-intensive if you’re doing it in the Java® language.

Important note: I will be referring to lambdas frequently going forward. Before continuing, be sure you understand what that means in the context of computer programming, even if not specifically for Kotlin. In short, it’s a way of expressing an anonymous function that you would pass inline to another function or assign to a variable.

The core feature of Kotlin that makes type-safe builders possible is called lambda with receiver. Let’s get straight into an example that’s actually useful. Kotlin allows you to define functions outside of classes, and that’s all I’m doing here. Also note that the names of variables come before their types, which is the opposite of the Java language.

The above function is named v for brevity as I’ll use it a lot here and in future posts, and you can call it like this:

That’s equivalent to inflating an XML layout that looks like this:

Neat! Now, if this is your first time seeing Kotlin, there’s a lot to translate into English! Here’s a few bits of Kotlin syntax to unpack:

<reified TV : View>

init: TV.() -> Unit

In our specific case, function v is declaring, “I’m going to create an object of type TV, and I need you to tell me how to initialize it”. So this new TV type object becomes the receiver of the provided lambda, and the lambda is invoked by v with view.init() so it can perform some actions with the view. The “-> Unit” in the syntax is just saying that the lambda returns type Unit, which is like the type void in Java code. In other words, it returns nothing.

To summarize this lambda with receiver:

  • v declares a parameter called init which is a lambda with receiver for type TV.
  • v creates and initializes a TV type object and invokes the lambda on it to initialize it.
  • The lambda sees the TV type object as “this” in its chunk of code.

TV::class.java

At this point, I’m going to anticipate a couple more questions you might have about this function:

“Why does v take two arguments, but appear to be given only one inside the argument parenthesis?”

“Are ‘layoutParams’ and ‘text’ some sort of variables?”

Image for post
Image for post
The IDE’s autocomplete suggests which methods are backing Kotlin properties.

As you can see, the Kotlin plugin is pointing out to us that the property called “text” (among other properties) is derived from the underlying JavaBeans-style getter and setter methods of the TextView type receiver object.

“What is this Constructor business? Can’t we just say “new TV(context)”?”

That’s a whole lot of convenience for a few lines of code! If you’re new to Kotlin, you might want to go back and digest this a second time, because some of these concepts can be very foreign to Java programmers. It certainly took me a bit of studying to grok all this new stuff.

This is just the beginning of my experiment. There’s still many ways this function could be enhanced and made easier to use. For example, it would be great if we could build entire nested view hierarchies in a single expression. So stay tuned for the next post in this series to see how we can use Kotlin to do that!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store