Category: Software Development

Kotlin Reified Types in Inline Functions

Kotlin Reified Types in Inline Functions

I’ve noticed that many people haven’t ever heard of reified types or have problems understanding what they are, and what they do. Therefore this little post is intended to bring some light into the darkness of Kotlin’s reified types.

Starting situation

fun <T> myGenericFun(c: Class<T>)

In an ordinary generic function like myGenericFun you can’t access the type T because it’s, like in Java, erased at runtime and thus only available at compile time.  Therefore, if you want to use the generic type as a normal Class in the function body you need to explicitly pass the class as a parameter like the parameter c in my example. That’s correct and works fine but makes it a bit unsightly for the caller.

Inlined function with reified to the rescue

If, on the other hand, you use an inline function with a reified generic type T, the value of T can be accessed even at runtime and thus you don’t need to pass the Class<T> additionally. You can work with T as if it was a normal Class, e.g. you might want to check whether a variable is an instance of T, which you can easily do like this: myVar is T.

An inline function with reified type looks like this:

inline fun <reified T> myGenericFun()

Be aware, that reified types can only be used in combination with inline functions. Such an inline function makes the compiler copy the function’s bytecode into every place where the function is being called (we say the function is being “inlined“). When you call an inline function with reified type, the compiler knows the actual type used as a type argument and modifies the generated bytecode to use the corresponding class directly. Therefore calls like myVar is T become myVar is String (if the type argument were String) in the bytecode and at runtime.

Reified in Action

Let’s have a look at an example, where reified is really helpful. We want to create an extension function for String called toKotlinObject, which tries to convert a JSON string to a Kotlin Object, specified by the function’s type T. We can use com.fasterxml.jackson.module.kotlin for this and the first approach is the following:

Compile Error

fun <T> String.toKotlinObject(): T {
      val mapper = jacksonObjectMapper()
      //does not compile!
      return mapper.readValue(JsonObject(this).encode(), T::class.java)
}

The readValue method wants us to provide the information which type it’s supposed to parse the JsonObject to. We try to use the type parameter T and get its Class. This does not work and the compiler tells us: “Cannot use ‘T’ as reified type parameter. Use a class instead.”

Working example without reified

fun <T> String.toKotlinObject(c: Class<T>): T {
    val mapper = jacksonObjectMapper()
    return mapper.readValue(JsonObject(this).encode(), c)
}

In a next step we pass the Class of T explicitly which can directly be used as an argument to readValue. This works and is actually the same approach used in Java code for such scenarios. The function can be called like so:

"{}".toKotlinObject(MyJsonType::class.java)

With reified
Using an inline function with reified type parameter T makes it possible to implement our function as follows:

inline fun <reified T> String.toKotlinObject(): T {
    val mapper = jacksonObjectMapper()
    return mapper.readValue(JsonObject(this).encode(), T::class.java)
}

No need to pass the Class of T additionally, T can be used as if it was an ordinary class. For the client the code looks like this:

"{}".toKotlinObject<MyJsonType>()

Important
Inline reified functions are not callable from Java code, whereas normal inline functions are. That’s probably the reason why not every type parameter used in inline functions is reified by default.

Conclusion

This was just a quick introduction to reified types. In my opinion the call to a function with reified types looks way better because we can make use of the <> syntax commonly used whenever generics are relevant. As a result, it’s more readable than the Java approach of passing a Class object as a parameter. All the dirty details can be read in this specification document.

If you want to read more about Kotlin’s beautiful features I recommend the book Kotlin in Action to you and also like to direct you to my other articles 🙂

Keep coding!

Cheers, Simon.

Please follow and like me 🙂
Spring WebFlux with Kotlin – Reactive Web

Spring WebFlux with Kotlin – Reactive Web

Spring – even more fancy

As you might most certainly know, I’m one of these Kotlin “hipsters”, who’s really loving the language and wouldn’t write any more Java, if it was that easy. If you’re not familiar with my articles, have a look at the other Kotlin related posts here.

Read More Read More

Please follow and like me 🙂
Creating DSL with Kotlin – Introducing a TLSLibrary

Creating DSL with Kotlin – Introducing a TLSLibrary

Creating DSL with Kotlin

Introducing a TLSLibrary

Motivation

If you’ve been following my recent posts about Kotlin, you’ve probably noticed me mentioning Domain Specific Languages (DSL) already. Kotlin as a programming language provides some powerful features that allow us to create those DSLs. One of these features, I also already introduced, is called Function Literals with Receiver, others are the invoke convention or infix notation.

In this post we’ll have a look at the concept of DSLs and certainly see how we can create one with Kotlin in a relatively simple example:
I’ve often been struggling with Java’s API for setting up SSL/TLS connections in scenarios where https communication is required for example. Just recently, I had to implement different kinds of these in one of our applications. Doing this, I once again felt like wanting to write a little library that can support me with that task, hiding away all the difficulties and of course the boilerplate.

Read More Read More

Please follow and like me 🙂
Kotlin Conventions – Operator Overloading

Kotlin Conventions – Operator Overloading

Operator Overloading and Conventions in Kotlin

Introduction

Kotlin supports a technique called conventions, everyone should be familiar with. For example, if you define a special method plus in your class, you can use the + operator by convention.
In this article I want to show you which conventions can be used and will provide some Kotlin code demonstrating the concepts of course.

Read More Read More

Please follow and like me 🙂
Kotlin Function Literals with Receiver – Quick Introduction

Kotlin Function Literals with Receiver – Quick Introduction

Function Literals with Receiver – The Foundation for DSLs and many Library Functions

Today I want to give a quick introduction to Function Literals with Receiver. This concept is what makes Kotlin great for designing Domain Specific Languages as we know it from Groovy for example. Also, Kotlins standard library includes many functions which many of you have already used or at least seen probably: apply and with are the most prominent ones.

Read More Read More

Please follow and like me 🙂
Kotlin on the JVM – Bytecode Generation

Kotlin on the JVM – Bytecode Generation

Kotlin on the JVM – How can it provide so many features?

Introduction

What exactly is a “JVM language”? Isn’t only Java meant to be run on the JVM?
Kotlin provides many features that aren’t available in Java such as a proper function type, extension functions or data classes. How was this even achievable? I’ve taken a deeper look at how Kotlin is made possible and what “JVM language” actually means. We’ll be having a look at Kotlin’s bytecode generation. I hope to help some people understanding a few things better 🙂

For a more detailed introduction to Kotlin’s features you can have a look at my recent posts like this one.

Please follow and like me 🙂
Sealed Classes in Kotlin – An Explanation

Sealed Classes in Kotlin – An Explanation

Sealed Classes in Kotlin – An Explanation

Today I came across Sealed Classes in Kotlin, which I had never heard of before. After some research I found that this concept is nothing new and is also available in Scala for example. So, yet another Scala feature JetBrains considered relevant and suitable for Kotlin? I like that 🙂 Read this post if you’re interested in more Kotlin features.

Actually this is a quite simple feature, which I’m going to explain in the following.

Feature Explanation

A sealed class can be subclassed and may include abstract methods which means sealed classes are abstract implicitly, although the documentation doesn’t clearly say so. To actually make a class “sealed” we have to put the sealed modifier before its name, as we can see here:

sealed class MyClass

Restriction

The important thing about sealed classes is that its subclasses must be declared in the same file as the sealed class itself.

Benefit

The feature allows us to define class hierarchies that are restricted in its’ types, i.e. subclasses. Since all subclasses need to be defined inside the file of the sealed class, there’s no chance of unknown subclasses which the compiler doesn’t know about.

Wait… Isn’t this what an enum actually is?

Kotlin’s sealed classes are some kind of extension of plain enums: As opposed to enums, subclasses of sealed classes can be instantiated multiple types and can actually contain state.

Use Case

The main advantage of sealed classes reveals itself if it’s used in when expressions. Let’s compare a normal class hierarchy to one of a sealed class handled in a when. First, we’ll create a hierarchy of Mammals and then put it in a method with a when:

open class Mammal(val name: String)
class Cat(val catName: String) : Mammal(catName)
class Human(val humanName: String, val job: String) : Mammal(humanName)
fun greetMammal(mammal: Mammal): String {
    when (mammal) {
        is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}"
        is Cat -> return "Hello ${mammal.name}"
        else -> return "Hello unknown"
    }
}

The else is mandatory, otherwise the compiler will complain. This is because it just cannot verify that all possible cases, i.e. subclasses, are covered here. It may be possible that a subclass Dog is available at any time which is unknown at compile time.

Sealed “to the rescue”

But what if we knew there wouldn’t be other Mammals in our application? We’d want to leave out that else.

The problem of unknown subclasses can be avoided by sealed classes. Let’s modify the base class Mammal, its’ subclasses can remain the same.

sealed class Mammal(val name: String)

Now we can simply omit the else clause since the compiler can verify that all possible cases are covered because only the subclasses in the file of the sealed class exist, without exception. The method now looks as follows:

fun greetMammal(mammal: Mammal): String {
    when (mammal) {
        is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}"
        is Cat -> return "Hello ${mammal.name}"
        // `else` clause not required, all the cases covered 
    }
}

That’s it. In conclusion really simple and handy, isn’t it? Have fun trying it yourself!

I’m going to create an example in KotlinByExample for this topic as soon as possible.

Finally, if you want to read about sealed classes in more detail I recommend the book Kotlin in Action to you!

Simon


 

Please follow and like me 🙂
Generic Types and Variance in Kotlin compared to Java

Generic Types and Variance in Kotlin compared to Java

Basics – What is Variance?

Many programming languages support the concept of subtyping, which allows us to implement hierarchies like “A Cat IS-An Animal“. In Java we can either use the extends keyword in order to change/expand behaviour of an existing class (inheritance) or use implements to provide implementations for an interface. According to Liskov’s substitution principle, every instance of a class A can be substituted by instances of its subtype B. The word variance, often referred to in mathematics as well, is used to describe how subtyping in complex aspects like method return types, type declarations, generic types or arrays relates to the direction of inheritance of the involved classes. There are three terms we need to take into account: Covariance, Contravariance and Invariance.

Read More Read More

Please follow and like me 🙂
Setup Vert.x Application written in Kotlin (Gradle Build)

Setup Vert.x Application written in Kotlin (Gradle Build)

I decided to write a Vert.x application in combination with Kotlin in a simple example because I’m really interested in Reactive Programming and love to use Kotlin. This post will give some basic information on Vert.x as a tool set for writing reactive applications on the JVM as well as a few words on Kotlin. In the end, I want to demonstrate how this application can be set up in Gradle. Of course, this will be just one out of a million possible solutions…​

Read More Read More

Please follow and like me 🙂
Java Oracle Certification

Java Oracle Certification

Java Oracle Certification – Should you consider it?

I took the OCA SE 7 Programmer I Certification exam two years ago in 2015, which I passed successfully with a score of 86%. This year I will be taking the second exam of this certification path called OCP SE 7 Programmer II. In this post I want to reflect why taking these kind of exams isn’t a waste of time but can be a great advantage for you as a Java developer. Of course, being certified in whatever area will increase your chances of getting a better job because certificates represent some kind of guaranty of your skills to a company. No doubt about that.

Read More Read More

Please follow and like me 🙂

Enjoy this blog? Please spread the word :)