Better Programming

Advice for programmers.

Follow publication

Member-only story

How to Use Generics in Kotlin

Farhan Tanvir
Better Programming
Published in
3 min readMar 23, 2022

Photo by Marc Reichelt on Unsplash

As a developer, one of our main duty is to keep the code as minimal as possible and avoid repeated code. Generics is one of the functionalities which provides better performance, less code, reusable code, and many more. So I believe every developer should have knowledge about Generics.

Why do we need Generics?

As we can see, SearchUtil class will take a list of Integers as a parameter. searchItem function will take an integer (which needed to be searched) as an input and return the result. This seems fine. isn’t it ?. Then what's the problem?

Suppose, now you have to search for an item that is a list of strings or objects. What will you do? There are two possible solutions to this problem.

  1. Create another SearchUtil class and searchItem function which will take the strings or object type and return the result.
  2. Use Generics

Solution 1 is obviously is not a good idea. Because we have to write lots of code and many codes will be repeated. In this scenario, Generics comes to the rescue.

What is Generics?

According to official documentation,

Generics are classes, structures, interfaces, and methods that have placeholders (type parameters) for one or more of the types that they store or use. A generic collection class might use a type parameter as a placeholder for the type of objects that it stores; the type parameters appear as the types of its fields and the parameter types of its methods. A generic method might use its type parameter as the type of its return value or as the type of one of its formal parameters.

In a nutshell,

Generics is a flexible system that allows you to work with any data types. It changes the type burdens from you to compiler .

I think this is the simplest explanation.

Generics in Action

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Farhan Tanvir
Farhan Tanvir

Written by Farhan Tanvir

Believes in learn by doing . Currently working as a software engineer. Love to share Knowledge. https://twitter.com/FarhanTanvirBD

Responses (1)

Write a response