How to work with Generics in Kotlin
Generic methods and classes help us use the same method or class for various types. This improves code reusability. In this recipe, we will understand Generics and how to use it in Kotlin. Generics in Kotlin is quite similar to Generics in Java, but there are additional special keywords in Kotlin that make Generics in Kotlin more intuitive. Let's dive in.
Getting ready
You need to install a preferred development environment that compiles and runs Kotlin. You can also use the command line for the purpose, for which you need a Kotlin compiler installed along with JDK. I am using IntelliJ IDE to compile and run my Kotlin code for this recipe.
How to do it…
Now, let's follow these steps to understand how Generics works in Kotlin, with the help of some examples:
- Let's start with a generic class that we can instantiate using any type of parameter:
fun main(args: Array<String>) { val intgen: GenCl<Int> = GenCl<Int>(10) println(intgen.a) ...