Sirwin
Sirwin
Kotlin spotlight

Kotlin 1.4 : Performant, Modern, Fresh

By ProngsDark | Pr0gram Failure | 19 Apr 2020


As we approach the inevitable release of the 1.4 version of the Kotlin programming language, I thought that this is a great time to take a look at what is new, what is changed and how this update will influence our future work. Note that this article is meant to highlight the practical usage of some of the new features and to clear some of the technical jargon used in the official release notes, for a more detailed and technical review check the resources at the bottom of the article.

1. General improvements and Kotlin/JVM

When developing with Kotlin, my guess is that most people will use it to make projects for the JVM (Java Virtual Machine) that are compatible with Java and are to be run through it. In this category are included those that create Android applications using Kotlin, thus making it the most important use-case for the language.

  1.1 'SAM' conversions for functions and interfaces

'SAM' stands for Single Abstract Method and refers to a concept in programming where an Interface with a single method can be used through a Lambda method. A compiler that allows for such an operation to take place can convert from the Lambda method to the Interface type and vice versa. 

  Why is this useful in practice?

There are several reasons why such a an operation is useful and they include things like: easy creation of objects that implement that Interface and creating multiple handler functions that can be used to override the one from the Interface.

The example given by the official Kotlin team is:

fun interface Action {
    fun run()
}

fun runAction(a: Action) = a.run()

fun main() {
    runAction {
        println("Hello, Kotlin 1.4!")
    }
}

If you are familiar with this kind of stuff in Java then take notice that in Kotlin the interface needs to be explicitly marked as fun interface in order for the conversion to work.

  1.2 Powerful type inference

The team says that the new algorithm is better and more powerful than ever and with the amount of work that has gone into implementing it we can rest assured that this new feature has some incredible practical use case scenarios. Let's take a look at the example from the Kotlin team and discuss it a little:

val rulesMap: Map<String, (String?) -> Boolean> = mapOf(
    "weak" to { it != null },
    "medium" to { !it.isNullOrBlank() },
    "strong" to { it != null && "^[a-zA-Z0-9]+$".toRegex().matches(it) }
)

For those of you unfamiliar with Kotlin I mention that String? is a syntactic-sugar datatype that refers to a String or null. In the example above we can see a Map with a String key and a lambda function as value. The lambda will receive a String? and return a Boolean value. The interesting aspect of the example is how Kotlin "knows" (infers) the type of the it variableas being String? (in Kotlin it is an inferred object that is used in lambda functions like mapOf() ). In previous versions this kind of clean and readable syntax wouldn't have been possible and it would have required a little more technical work. 

  1.3 Contract support

In programming there are multiple ways to write software, those are known as design choices. One such design carries the name of contract based programming. Writing software following this idea means that you define function behaviour on the premise that a certain set of preconditions has been met and your function will provide to the client that's calling it a result that is known beforehand. This is based on the real world way of how contracts work: there are conditions that one or both parties have to meet before the contract is signed and after it's signed then the exchange or receiving of goods takes place.

In the official example we will look at a typical assert function:

@OptIn(ExperimentalContracts::class)
inline fun <reified T> assertIsInstance(value: Any?) {
    contract {
        returns() implies (value is T)
    }

    assertTrue(value is T)
}

The assertIsInstance() function makes the assertion that some value is of some type T, those things are "stipulated" in our contract. Breaching this assertion will result in error.

I am not a big fan of this design since there are many impracticalities that come along with it.

Kotlin/JS

2. Kotlin/JS

Yes in case you didn't know Kotlin can be used to write JavaScript programs and the 1.4 release comes with a huge update for the users of Kotlin/JS.

  2.1 IR compiler

IR stands for Intermediate Representation and refers to the way a compiler rewrites your code to be easier to optimise, analyse and rearrange before it is transformed into machine-code. This new compiler means your code will be more optimised, thus making your program faster and easier to execute by the computer. 

To use the new compiler backend you need to type the following in your gradle.properties file: kotlin.js.compiler=ir

  2.2 Improved DCE

DCE or Dead Code Elimination is a process that allows the compiler to identify and delete the code in your program that will never be used before actually creating the executable. This way the size of the executable is reduced. 

In Kotlin/JS this feature improvement is dependent on the aforementioned IR compiler and the size reduction is pretty visible when comparing with the old compiler.

IR compiler vs old compiler

Kotlin/Native

3. Kotlin/Native

Don't want to run your code for the Java Virtual Machine, or want to make iOS apps or Windows apps? Well... Kotlin pretty much can do anything you want through the Native technology. A full list of the possible targets for your native code can be found here.

  3.1 Objective-C generics are supported by default

Generics refer to the way you can write classes and functions that work for multiple datatypes. Note that this change in Kotlin will probably break previous code that was written in interoperability with Objective-C and Swift code.

Other changes are related to performance which has been improved and enabling some experimental features can even lead to two times the speed in some cases.

 

Conclusion:

This appears to be an incremental update, with focus on performance and optimisations. There are a couple of new features thrown in that will make programming with Kotlin even more pleasant and easier making it possibly one of the best languages to start programming with since it is such a breeze to understand it.

I hope I cleared some of the things that were included in the official documentation of the update and I also hope I made it clearer why those features are important in practice and how we could use some of that stuff.

If you have other questions or want to express your opinion on this article, don't hesitate to comment down bellow. Any feedback is highly appreciated and I strive to become a better writer by taking your opinions into consideration.

Thanks for reading!

 

 

How do you rate this article?

5


ProngsDark
ProngsDark

Happily married to a wonderful woman. Linux enthusiast, software developer and hacker of all things.


Pr0gram Failure
Pr0gram Failure

A blog dedicated to development subjects that every programmer deals with all the time. Simple things we all google and then ask ourselves "are we even developers?" or things we do when writing software that we are ashamed of and would never share with others. This blog is dedicated to the average Joe of programming.

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.