Explanation: Hey Kotlin, how it works?

Chang W. Doh
TIL: Kotlin in Practice
7 min readNov 26, 2017

This article is some explanations of my talk at GDG DevFest Seoul 2017. Hope this help of you to understand how Kotlin works. :)

If you wanna read this in Korean, please visit here.

You can find this slide at my SpeakerDeck

Caution: This is just a short journey to guess purpose of each code generation and its reason(or some painpoints) in Kotlin. Never think Kotlin is something like JVM wrapper.

Introduction to Kotlin Bytecode Inspector

I guess so many people’re curious about how Kotlin works internally. You can solve it by reading references, articles. However, I just would liked to show one more thing. :)

Showing decompiled Java code by Kotlin Bytecode Inspector

Search Everywhere(Shift > Shift) > Show Kotlin Bytecode will show equivalent Bytecode of your Kotlin code. If you click Decompile button, you can also check decompiled Java code is equivalent with your Kotlin code. If you are already familiar with Java, this can help you understand the code.

Basic features

Let’s take a quick look at some very basic stuffs of Kotlin.

The code above is a very simple Kotlin class, but there are some unfamiliar parts to those who have not used languages with similar syntax. Let’s take a look.

val vs var

val means value, and var means variable. It is not complicated. The value itself has an immutable value that does not change its value initially. Conversely, the value of a variable can change at any time.

Basically, variables and properties defined with val and var have own access limitations from the language level, and the easiest way to see this is through properties.

property

A property provides an interface for writing or reading a value as part of an object. In this case, the reading operation is called a getter, and the writing operation is called a setter. The important thing about a getter / setter is that it can be involved in other members of the object or in any calculation process when the value is set or read.

As mentioned earlier, declaring a property through var, which has both read / write properties, can be seen from Java code like this:

  • The field of declared field is protected from external access private.
  • Accessing the field is performed by generated getter and setter.

Then, what about val?

Is it similar? However, with a read-only attribute, setters are omitted and only getters are generated.

local variable

Now, let’s see local variables.

No footprints of getters or setters are visible. The code is generated as we normally declare it. If so, can local variables be freely accessed? It’s not like that. It is not allowed to perform assignments on variables declared by val because the difference between the value and the variable is already handled at the language level.

Nullable vs NotNull

You should have heard that Kotlin is Null-safe. Although the inventor said it was a mistake, the null is a very old invention. To solve null problem, modern programming languages introduced a approach of distinguishing between Nullable and NotNull, and Kotlin is one of them. Let’s look at the code.

Usual way to declare a type, it means NotNull. If you wanna check this out, you can see a function call checkParameterIsNotNull() in setter from decompiled code. This function is to check value is null for setting property and if it is, throw NPE(Null Pointer Exception).

Checking NotNull is same even at function arguments

Some of you could be curious about overhead from these null check. Yes, indeed, however, it’s enough small to ignore its influence, and also would be much more beneficial influence in your development process.

And, yes, Kotlin is also good at optimizing generated codes.

String template

From log messages for debugging to texts for toasting messages, string is the one of most important parts in programming. But, sometimes making a appropriate string can be a tedious work.

To solve this, Kotlin introduced String template. By describing string interpolation such as $identifier or ${expression} formatted, we could get the string we wanna make. Let’s see the code:

Decompile the above code as follows:

You would also worry about that using String concatenation will produce new strings at the each section. You can see codes with StringBuilder instead of string concatenation, so you can use String template with an easy mind.

Inheritance

Unlike other languages, Kotlin’s classes are limited to inherit by default. It’s the same as final class in Java.

As you can see from the above code, generated class got final by default. So, if you wanna extend the class, you should set it open or abstract with the foresight for the inheritance.

Perhaps Koltlin language designers would liked to reduce problems caused by unintended class inheritances.

In this situation, we can choose another design pattern to combine small and functional units rather than inheritances, and Delegation would be nice for it. If you’re interested in delegation, please refer to links at the end of this article.

Constructor, Initializer, Property declaration

In Kotlin, the way responsible for initializing a class can be divided into three stuffs:

  • Constructor
  • Initializer
  • Property declaration

Constructor

First, let’s take a look of constructor.

if there’s no modifier thing in primary constructor, you can omit the keyword ‘constructor’.

In the constructor, if any argument doesn’t have val or var, it just works as arguments passing to constructor function. But, if you declare arguments with val or var, they become properties of the class as the below:

Initializer

Initializer is the common parts to initialize the instance but not depended on arguments passing.

You can see the code of Initializer will placed in constructor from the generated Bytecode. :)

Constructor delegation

Also, you can define the constructor which will be called when constructor is called. This will be called Constructor delegation, and it’s always called just before executing constructor body.

The sequence of initializing the instance

When object is initializing in Kotlin, the sequence is as follows:

  • Constructor argument
  • Constructor delegation call
  • Property declarations
  • Initializer
  • Constructor body

If you thought about the above initializations, this sequence would be very natural. But, there’s a possibility to be confused, so that you should remember the sequence of the following code execution.

If you wanna learn more, visit An in-depth look at Kotlin’s initializers

Custom getter/setter

We have learned earlier that Kotlin’s property declaration includes an automated generating getter/setter. In addition to these, we can directly involve in accessing values.

Custom getter

You can access a property directly by a defined get(). It is optional for the property to store the actual value in a 1: 1 relation, so it is possible to define a field that refers to another field and performs only the calculation as described above.

Caution when writing custom setter

Also, setting value by set() is also possible in same way as defining ordinary function, however there’s something to be aware of. Let’s see the following code:

OMG, recursive call…

Assignment to store value into the fieldage calls setAge(). However, setter defined in age will try to set value into age, so it call itself continuously. To put it plainly concisely, yes, recursive call. As finally, result will be stack overflow.

So, what’s describing backing field of property itself? it’s using the keyword field. Likely this, field means appropriate property itself in the context.

When writing a setter of the property, always use field instead of property name. It help of you to prevent from recursive call.

Wanna know delegations in Kotlin?

In this article, we’ve taken a look of basic features of Kotlin. If you want to learn more about how the delegation of class or property works that are described in the rest parts of slides, visit the following links:

And about extensions and inline will be translated sooner. I expect I’m a hardworking writer and translator…:)

--

--

Chang W. Doh
TIL: Kotlin in Practice

I’m doing something looks like development. Community diver. ex-Google Developer Expert for Web 😎