Android - Build a Book Library App using Kotlin
Last Updated :
23 Jul, 2025
There are so many apps that are present in the play store which provides details related to different books inside it. Book Library is considered one of the basic applications which a beginner can develop to learn some basic concepts within android such as JSON parsing, using recycler view, and others. In this article, we will be building a simple Book Library application to display different types of books. We will be using Google Books API for building this application.
Note: If you are looking to build a Book Library application using Google Books API in android using Java. Check out the following article: How to Build a Book Library App using Google Books API in Android using Java
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add the dependency for Volley in your Gradle files
Navigate to the app > Gradle Scripts > build.gradle file and add the below dependency in the dependencies section.
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.squareup.picasso:picasso:2.71828'
After adding the below dependencies in your Gradle file now sync your project to install dependencies.
Step 3: Adding permissions for the Internet
Navigate to the app > AndroidManifest.xml and add the below permissions to it.
XML
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 4: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<!--on below line we are creating a swipe to refresh layout-->
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fillViewport="true"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/idLLsearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="5">
<!--edit text for getting the search
query for book from user-->
<EditText
android:id="@+id/idEdtSearchBooks"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4" />
<!--image button for our search button -->
<ImageButton
android:id="@+id/idBtnSearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/ic_search" />
</LinearLayout>
<!--recycler view for displaying our list of books-->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/idRVBooks"
android:layout_width="match_parent"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
android:layout_height="match_parent"
android:layout_below="@id/idLLsearch" />
<!--progressbar for displaying our loading indicator-->
<ProgressBar
android:id="@+id/idLoadingPB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
</RelativeLayout>
Step 5: Creating a Modal Class for storing our data from the API
For creating a new Modal class. Navigate to the app > java > your app’s package name > Right-click on it and Click on New > Kotlin class and give a name to our java class as BookRVModal and add the below code to it. Comments are added in the code to get to know in more detail.
Kotlin
package com.gtappdevelopers.kotlingfgproject
data class BookRVModal(
// creating string, int and array list
// variables for our book details
var title: String,
var subtitle: String,
var authors: ArrayList<String>,
var publisher: String,
var publishedDate: String,
var description: String,
var pageCount: Int,
var thumbnail: String,
var previewLink: String,
var infoLink: String,
var buyLink: String
)
Step 6: Create a new layout resource file
Go to the app > res > layout > right-click > New > Layout Resource File and name the file as book_item and add the following code to this file.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
app:cardCornerRadius="5dp"
app:cardElevation="4dp">
<!--on below line we are creating a
linear layout for grid view item-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--on below line we are creating
a simple image view-->
<ImageView
android:id="@+id/idIVBook"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_gravity="center"
android:layout_margin="8dp"
android:padding="5dp"
android:scaleType="fitCenter"
android:src="@mipmap/ic_launcher" />
<!--on below line we are creating
a simple text view-->
<TextView
android:id="@+id/idTVBookName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:lines="2"
android:maxLines="2"
android:padding="4dp"
android:text="@string/app_name"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="12sp"
android:textStyle="bold"
tools:ignore="RtlCompat" />
<!--on below line we are creating
a text view for page number-->
<TextView
android:id="@+id/idTVBookPages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:text="Book Pages"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="10sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
Step 7: Creating a new Activity for displaying our Book Info in detail
Navigate to the app > java > your app’s package name > Right-click on it and click on New > Activity > Select Empty Activity and name it as BookDetailsActivity. Make sure to select Empty Activity.
Step 8: Creating an Adapter class for setting our data to the item of RecyclerView
Navigate to the app > java > your app’s package name > Right-click on it Click on New > Kotlin class and name it as BookRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail.
Kotlin
package com.gtappdevelopers.kotlingfgproject
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
class BookRVAdapter(
// on below line we are passing variables
// as course list and context
private var bookList: ArrayList<BookRVModal>,
private var ctx: Context
) : RecyclerView.Adapter<BookRVAdapter.BookViewHolder>() {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): BookRVAdapter.BookViewHolder {
// this method is use to inflate the layout file
// which we have created for our recycler view.
// on below line we are inflating our layout file.
val itemView = LayoutInflater.from(parent.context).inflate(
R.layout.book_item,
parent, false
)
// at last we are returning our view holder
// class with our item View File.
return BookRVAdapter.BookViewHolder(itemView)
}
override fun onBindViewHolder(holder: BookRVAdapter.BookViewHolder, position: Int) {
val bookInfo = bookList.get(position)
// below line is use to set image from URL in our image view.
Picasso.get().load(bookInfo.thumbnail).into(holder.bookIV);
holder.bookTitleTV.text = bookInfo.title
holder.bookPagesTV.text = "Pages : " + bookInfo.pageCount
// below line is use to add on click listener for our item of recycler view.
holder.itemView.setOnClickListener {
// inside on click listener method we are calling a new activity
// and passing all the data of that item in next intent.
val i = Intent(ctx, BookDetailsActivity::class.java)
i.putExtra("title", bookInfo.title)
i.putExtra("subtitle", bookInfo.subtitle)
i.putExtra("authors", bookInfo.authors)
i.putExtra("publisher", bookInfo.publisher)
i.putExtra("publishedDate", bookInfo.publishedDate)
i.putExtra("description", bookInfo.description)
i.putExtra("pageCount", bookInfo.pageCount)
i.putExtra("thumbnail", bookInfo.thumbnail)
i.putExtra("previewLink", bookInfo.previewLink)
i.putExtra("infoLink", bookInfo.infoLink)
i.putExtra("buyLink", bookInfo.buyLink)
// after passing that data we are
// starting our new intent.
ctx.startActivity(i)
}
}
override fun getItemCount(): Int {
return bookList.size
}
class BookViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
// on below line we are initializing our
// course name text view and our image view.
val bookTitleTV: TextView = itemView.findViewById(R.id.idTVBookName)
val bookPagesTV: TextView = itemView.findViewById(R.id.idTVBookPages)
val bookIV: ImageView = itemView.findViewById(R.id.idIVBook)
}
}
Step 9: Working with the activity_book_details.xml file
Navigate to app>res>layout>activity_book_details.cml file and add the below code to it. Comments are added in the code to get to know in detail.
XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BookDetailsActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!--Image view for displaying our book image-->
<ImageView
android:id="@+id/idIVbook"
android:layout_width="130dp"
android:layout_height="160dp"
android:layout_margin="18dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="vertical">
<!--Text view for displaying book publisher-->
<TextView
android:id="@+id/idTVpublisher"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:text="Publisher"
android:textColor="@color/black"
android:textSize="15sp" />
<!--text view for displaying number of pages of book-->
<TextView
android:id="@+id/idTVNoOfPages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:padding="4dp"
android:text="Number of Pages"
android:textColor="@color/black"
android:textSize="15sp" />
<!--text view for displaying book publish date-->
<TextView
android:id="@+id/idTVPublishDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:padding="4dp"
android:text="Publish Date"
android:textColor="@color/black"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<!--text view for displaying book title-->
<TextView
android:id="@+id/idTVTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:padding="4dp"
android:text="title"
android:textColor="@color/black"
android:textSize="15sp" />
<!--text view for displaying book subtitle-->
<TextView
android:id="@+id/idTVSubTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:padding="4dp"
android:text="subtitle"
android:textColor="@color/black"
android:textSize="12sp" />
<!--text view for displaying book description-->
<TextView
android:id="@+id/idTVDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:padding="4dp"
android:text="description"
android:textColor="@color/black"
android:textSize="12sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:orientation="horizontal"
android:weightSum="2">
<!--button for displaying book preview-->
<Button
android:id="@+id/idBtnPreview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:layout_weight="1"
android:text="Preview"
android:textAllCaps="false" />
<!--button for opening buying page of the book-->
<Button
android:id="@+id/idBtnBuy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:layout_weight="1"
android:text="Buy"
android:textAllCaps="false" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Step 10: Working with the BookDetailsActivity.kt file
Go to the BookDetailsActivity.kt file and refer to the following code. Below is the code for the BookDetailsActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package com.gtappdevelopers.kotlingfgproject
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.squareup.picasso.Picasso
class BookDetailsActivity : AppCompatActivity() {
// creating variables for strings,text view,
// image views and button.
lateinit var titleTV: TextView
lateinit var subtitleTV: TextView
lateinit var publisherTV: TextView
lateinit var descTV: TextView
lateinit var pageTV: TextView
lateinit var publisherDateTV: TextView
lateinit var previewBtn: Button
lateinit var buyBtn: Button
lateinit var bookIV: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_book_details)
// initializing our variables.
titleTV = findViewById(R.id.idTVTitle)
subtitleTV = findViewById(R.id.idTVSubTitle)
publisherTV = findViewById(R.id.idTVpublisher)
descTV = findViewById(R.id.idTVDescription)
pageTV = findViewById(R.id.idTVNoOfPages)
publisherDateTV = findViewById(R.id.idTVPublishDate)
previewBtn = findViewById(R.id.idBtnPreview)
buyBtn = findViewById(R.id.idBtnBuy)
bookIV = findViewById(R.id.idIVbook)
// getting the data which we have passed from our adapter class.
val title = getIntent().getStringExtra("title")
val subtitle = getIntent().getStringExtra("subtitle")
val publisher = getIntent().getStringExtra("publisher")
val publishedDate = getIntent().getStringExtra("publishedDate")
val description = getIntent().getStringExtra("description")
val pageCount = getIntent().getIntExtra("pageCount", 0)
val thumbnail = getIntent().getStringExtra("thumbnail")
val previewLink = getIntent().getStringExtra("previewLink")
val infoLink = getIntent().getStringExtra("infoLink")
val buyLink = getIntent().getStringExtra("buyLink")
// after getting the data we are setting
// that data to our text views and image view.
titleTV.setText(title)
subtitleTV.setText(subtitle)
publisherTV.setText(publisher)
publisherDateTV.setText("Published On : " + publishedDate)
descTV.setText(description)
pageTV.setText("No Of Pages : " + pageCount)
Picasso.get().load(thumbnail).into(bookIV)
// adding on click listener for our preview button.
previewBtn.setOnClickListener {
if (previewLink.isNullOrEmpty()) {
// below toast message is displayed
// when preview link is not present.
Toast.makeText(
this@BookDetailsActivity,
"No preview Link present",
Toast.LENGTH_SHORT
)
.show()
}
// if the link is present we are opening
// that link via an intent.
val uri: Uri = Uri.parse(previewLink)
val i = Intent(Intent.ACTION_VIEW, uri)
startActivity(i)
}
// adding click listener for buy button
buyBtn.setOnClickListener {
if (buyLink.isNullOrEmpty()) {
// below toast message is displaying
// when buy link is empty.
Toast.makeText(
this@BookDetailsActivity,
"No buy page present for this book",
Toast.LENGTH_SHORT
).show()
}
// if the link is present we are opening
// the link via an intent.
val uri = Uri.parse(buyLink)
val i = Intent(Intent.ACTION_VIEW, uri)
startActivity(i)
}
}
}
Step 11: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package com.gtappdevelopers.kotlingfgproject
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
class MainActivity : AppCompatActivity() {
// on below line we are creating variables.
lateinit var mRequestQueue: RequestQueue
lateinit var booksList: ArrayList<BookRVModal>
lateinit var loadingPB: ProgressBar
lateinit var searchEdt: EditText
lateinit var searchBtn: ImageButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// on below line we are initializing
// our variable with their ids.
loadingPB = findViewById(R.id.idLoadingPB)
searchEdt = findViewById(R.id.idEdtSearchBooks)
searchBtn = findViewById(R.id.idBtnSearch)
// adding click listener for search button
searchBtn.setOnClickListener {
loadingPB.visibility = View.VISIBLE
// checking if our edittext field is empty or not.
if (searchEdt.text.toString().isNullOrEmpty()) {
searchEdt.setError("Please enter search query")
}
// if the search query is not empty then we are
// calling get book info method to load all
// the books from the API.
getBooksData(searchEdt.getText().toString());
}
}
private fun getBooksData(searchQuery: String) {
// creating a new array list.
booksList = ArrayList()
// below line is use to initialize
// the variable for our request queue.
mRequestQueue = Volley.newRequestQueue(this@MainActivity)
// below line is use to clear cache this
// will be use when our data is being updated.
mRequestQueue.cache.clear()
// below is the url for getting data from API in json format.
val url = "https://www.googleapis.com/books/v1/volumes?q=$searchQuery"
// below line we are creating a new request queue.
val queue = Volley.newRequestQueue(this@MainActivity)
// on below line we are creating a variable for request
// and initializing it with json object request
val request = JsonObjectRequest(Request.Method.GET, url, null, { response ->
loadingPB.setVisibility(View.GONE);
// inside on response method we are extracting all our json data.
try {
val itemsArray = response.getJSONArray("items")
for (i in 0 until itemsArray.length()) {
val itemsObj = itemsArray.getJSONObject(i)
val volumeObj = itemsObj.getJSONObject("volumeInfo")
val title = volumeObj.optString("title")
val subtitle = volumeObj.optString("subtitle")
val authorsArray = volumeObj.getJSONArray("authors")
val publisher = volumeObj.optString("publisher")
val publishedDate = volumeObj.optString("publishedDate")
val description = volumeObj.optString("description")
val pageCount = volumeObj.optInt("pageCount")
val imageLinks = volumeObj.optJSONObject("imageLinks")
val thumbnail = imageLinks.optString("thumbnail")
val previewLink = volumeObj.optString("previewLink")
val infoLink = volumeObj.optString("infoLink")
val saleInfoObj = itemsObj.optJSONObject("saleInfo")
val buyLink = saleInfoObj.optString("buyLink")
val authorsArrayList: ArrayList<String> = ArrayList()
if (authorsArray.length() != 0) {
for (j in 0 until authorsArray.length()) {
authorsArrayList.add(authorsArray.optString(i))
}
}
// after extracting all the data we are
// saving this data in our modal class.
val bookInfo = BookRVModal(
title,
subtitle,
authorsArrayList,
publisher,
publishedDate,
description,
pageCount,
thumbnail,
previewLink,
infoLink,
buyLink
)
// below line is use to pass our modal
// class in our array list.
booksList.add(bookInfo)
// below line is use to pass our
// array list in adapter class.
val adapter = BookRVAdapter(booksList, this@MainActivity)
// below line is use to add linear layout
// manager for our recycler view.
val layoutManager = GridLayoutManager(this, 3)
val mRecyclerView = findViewById<RecyclerView>(R.id.idRVBooks) as RecyclerView
// in below line we are setting layout manager and
// adapter to our recycler view.
mRecyclerView.layoutManager = layoutManager
mRecyclerView.adapter = adapter
}
} catch (e: Exception) {
e.printStackTrace()
}
}, { error ->
// in this case we are simply displaying a toast message.
Toast.makeText(this@MainActivity, "No books found..", Toast.LENGTH_SHORT)
.show()
})
// at last we are adding our
// request to our queue.
queue.add(request)
}
}
Now run your application to see the output of it.
Output:
Similar Reads
Kotlin Tutorial This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read
Overview
Introduction to KotlinKotlin is a statically typed, general-purpose programming language developed by JetBrains, which has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 as a new language for the JVM. Kotlin is an object-oriented language, and a better lang
4 min read
Kotlin Environment setup for Command LineTo set up a Kotlin environment for the command line, you need to do the following steps:Install the Java Development Kit (JDK): Kotlin runs on the Java virtual machine, so you need to have the JDK installed. You can download the latest version from the official Oracle website.Download the Kotlin com
2 min read
Kotlin Environment setup with Intellij IDEAKotlin is a statically typed, general-purpose programming language developed by JetBrains that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011. Kotlin is object-oriented language and a better language than Java, but still be fully i
2 min read
Hello World program in KotlinHello, World! It is the first basic program in any programming language. Let's write the first program in the Kotlin programming language. The "Hello, World!" program in Kotlin: Open your favorite editor, Notepad or Notepad++, and create a file named firstapp.kt with the following code. // Kotlin He
2 min read
Basics
Kotlin Data TypesThe most fundamental data type in Kotlin is the Primitive data type and all others are reference types like array and string. Java needs to use wrappers (java.lang.Integer) for primitive data types to behave like objects but Kotlin already has all data types as objects.There are different data types
3 min read
Kotlin VariablesIn Kotlin, every variable should be declared before it's used. Without declaring a variable, an attempt to use the variable gives a syntax error. The declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type o
2 min read
Kotlin OperatorsOperators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language. Example:Kotlinfun main(args: Array<String>) { var a= 10 + 20 println(a) }Output:30Explanation: Here, â+â is an additio
4 min read
Kotlin Standard Input/OutputIn this article, we will discuss how to take input and how to display the output on the screen in Kotlin. Kotlin standard I/O operations are performed to flow a sequence of bytes or byte streams from an input device, such as a Keyboard, to the main memory of the system and from main memory to an out
4 min read
Kotlin Type ConversionType conversion (also called as Type casting) refers to changing the entity of one data type variable into another data type. As we know Java supports implicit type conversion from smaller to larger data types. An integer value can be assigned to the long data type. Example: Javapublic class Typecas
2 min read
Kotlin Expression, Statement and BlockEvery Kotlin program is made up of parts that either calculate values, called expressions, or carry out actions, known as statements. These parts can be organized into sections called blocks. Table of ContentKotlin ExpressionKotlin StatementKotlin BlockKotlin ExpressionAn expression in Kotlin is mad
4 min read
Control Flow
Kotlin if-else expressionDecision Making in programming is similar to decision-making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. If t
4 min read
Kotlin while loopIn programming, loop is used to execute a specific block of code repeatedly until certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of loop you can save time and you need to write only two lines.While loopIt cons
2 min read
Kotlin do-while loopLike Java, the do-while loop is a control flow statement that executes a block of code at least once without checking the condition, and then repeatedly executes the block, or not, depending on a Boolean condition at the end of the do-while block. It contrasts with the while loop because the while l
2 min read
Kotlin for loopIn Kotlin, the for loop is equivalent to the foreach loop of other languages like C#. Here for loop is used to traverse through any data structure that provides an iterator. It is used very differently then the for loop of other programming languages like Java or C. The syntax of the for loop in Kot
4 min read
Kotlin when expressionIn Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match is found, it reaches to
6 min read
Kotlin Unlabelled breakWhen we are working with loops and want to stop the execution of loop immediately if a certain condition is satisfied, in this case, we can use either break or return expression to exit from the loop. In this article, we will discuss learn how to use break expression to exit a loop. When break expre
4 min read
Kotlin labelled continueIn this article, we will learn how to use continue in Kotlin. While working with a loop in programming, sometimes, it is desirable to skip the current iteration of the loop. In that case, we can use the continue statement in the program. continue is used to repeat the loop for a specific condition.
4 min read
Array & String
Functions
Kotlin functionsIn Kotlin, functions are used to encapsulate a piece of behavior that can be executed multiple times. Functions can accept input parameters, return values, and provide a way to encapsulate complex logic into reusable blocks of code. Table of ContentWhat are Functions?Example of a FunctionTypes of Fu
7 min read
Kotlin Default and Named argumentIn most programming languages, we need to specify all the arguments that a function accepts while calling that function, but in Kotlin, we need not specify all the arguments that a function accepts while calling that function, so it is one of the most important features. We can get rid of this const
7 min read
Kotlin RecursionIn this tutorial, we will learn about Kotlin Recursive functions. Like other programming languages, we can use recursion in Kotlin. A function that calls itself is called a recursive function, and this process of repetition is called recursion. Whenever a function is called then there are two possib
3 min read
Kotlin Tail RecursionIn a traditional recursion call, we perform our recursive call first, and then we take the return value of the recursive call and calculate the result. But in tail recursion, we perform the calculation first, and then we execute the recursive call, passing the results of the current step to the next
2 min read
Kotlin Lambdas Expressions and Anonymous FunctionsIn this article, we are going to learn lambdas expression and anonymous function in Kotlin. While syntactically similar, Kotlin and Java lambdas have very different features. Lambdas expression and Anonymous function both are function literals means these functions are not declared but passed immedi
6 min read
Kotlin Inline FunctionsIn Kotlin, higher-order functions and lambda expressions are treated like objects. This means they can use up memory, which can slow down your program. To help with this, we can use the 'inline' keyword. This keyword tells the compiler not to create separate memory spaces for these functions. Instea
5 min read
Kotlin infix function notationIn this article, we will learn about infix notation used in Kotlin functions. In Kotlin, a function marked with infix keyword can also be called using infix notation means calling without using parenthesis and dot. There are two types of infix function notation in KotlinTable of ContentStandard libr
5 min read
Kotlin Higher-Order FunctionsKotlin language has superb support for functional programming. Kotlin functions can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions. Higher-Order FunctionIn Kotlin, a function that can accept a function as a parameter or return a func
6 min read
Collections
Kotlin CollectionsIn Kotlin, collections are used to store and manipulate groups of objects or data. There are several types of collections available in Kotlin, including:Collection NameDescriptionLists Ordered collections of elements that allow duplicates.Sets Unordered collections of unique elements.Maps Collection
6 min read
Kotlin list : ArraylistThe ArrayList class is used to create a dynamic array in Kotlin. Dynamic array states that we can increase or decrease the size of an array as a prerequisite. It also provides read and write functionalities. ArrayList may contain duplicates and is non-synchronized in nature. We use ArrayList to acce
6 min read
Kotlin list : listOf()In Kotlin, a List is a generic, ordered collection of elements. Lists are very common in everyday programming as they allow us to store multiple values in a single variable. Kotlin provides two types of lists - Immutable Lists (which cannot be changed and created using listOf()) and Mutable Lists (w
7 min read
Kotlin Set : setOf()In Kotlin, a Set is a generic unordered collection of elements that does not allow duplicate elements. Kotlin provides two main types of sets:Immutable Set: Created using setOf() â supports only read-only operations.Mutable Set: Created using mutableSetOf() â supports both read and write operations.
4 min read
Kotlin hashSetOf()In Kotlin, a HashSet is a generic, unordered collection that holds unique elements only. It does not allow duplicates and provides constant-time performance for basic operations like add, remove, and contains, thanks to its internal hashing mechanism. The hashSetOf() function in Kotlin creates a mut
4 min read
Kotlin Map : mapOf()In Kotlin, a Map is a collection that stores data in key-value pairs. Each key in a map is unique, and the map holds only one value for each key. If a key is repeated, only the last value is retained.Kotlin distinguishes between:Immutable maps (mapOf()) - read-onlyMutable maps (mutableMapOf()) - rea
5 min read
Kotlin HashmapIn Kotlin, a HashMap is a collection that stores key-value pairs, where each key must be unique, but values can be duplicated. It is a hash table based implementation of the MutableMap interface. Map keys are unique and the map holds only one value for each key. It is represented as HashMap<key,
7 min read
OOPs Concept
Kotlin Class and ObjectsIn Kotlin, classes and objects are used to represent objects in the real world. A class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or fields), and implementations of behavior (member functions or methods). An object is an i
4 min read
Kotlin Nested class and Inner classIn Kotlin, you can define a class inside another class. Such classes are categorized as either nested classes or inner classes, each with different behavior and access rules.Nested ClassA nested class is a class declared inside another class without the inner keyword. By default, a nested class does
3 min read
Kotlin Setters and GettersIn Kotlin, properties are a core feature of the language, providing a clean and concise way to encapsulate fields while maintaining control over how values are accessed or modified. Each property can have getters and setters, which are automatically generated but can be customized as needed.Kotlin P
4 min read
Kotlin Class Properties and Custom AccessorsIn object-oriented programming, encapsulation is one of the most fundamental principles. It refers to bundling data (fields) and the code that operates on that data (methods) into a single unit - the class. Kotlin takes this principle even further with properties, a feature that replaces traditional
3 min read
Kotlin ConstructorA constructor is a special member function that is automatically called when an object of a class is created. Its main purpose is to initialize properties or perform setup operations. In Kotlin, constructors are concise, expressive, and provide significant flexibility with features like default para
6 min read
Kotlin Visibility ModifiersIn Kotlin, visibility modifiers are used to control the visibility of a class, its members (properties, functions, and nested classes), and its constructors. The following are the visibility modifiers available in Kotlin:private: The private modifier restricts the visibility of a member to the conta
6 min read
Kotlin InheritanceKotlin supports inheritance, which allows you to define a new class based on an existing class. The existing class is known as the superclass or base class, and the new class is known as the subclass or derived class. The subclass inherits all the properties and functions of the superclass, and can
10 min read
Kotlin InterfacesIn Kotlin, an interface is a collection of abstract methods and properties that define a common contract for classes that implement the interface. An interface is similar to an abstract class, but it can be implemented by multiple classes, and it cannot have state.Interfaces are custom types provide
7 min read
Kotlin Data ClassesIn Kotlin, we often create classes just to hold data. These are called data classes, and they are marked with the data keyword. Kotlin automatically creates some useful functions for these classes, so you donât have to write them yourself.What Is a Data Class?A data class is a class that holds data.
3 min read
Kotlin Sealed ClassesKotlin introduces a powerful concept that doesn't exist in Java: sealed classes. In Kotlin, sealed classes are used when you know in advance that a value can only have one of a limited set of types. They let you create a restricted class hierarchy, meaning all the possible subclasses are known at co
4 min read
Kotlin Abstract classIn Kotlin, an abstract class is a class that cannot be instantiated and is meant to be subclassed. An abstract class may contain both abstract methods (methods without a body) and concrete methods (methods with a body).An abstract class is used to provide a common interface and implementation for it
5 min read
Enum Classes in KotlinIn programming, sometimes we want a variable to have only a few specific values. For example, days of the week or card suits (like Heart, Spade, etc.). To make this possible, most programming languages support something called enumeration or enum.Enums are a list of named constants. Kotlin supports
4 min read
Kotlin extension functionKotlin provides a powerful feature called Extension Functions that allows us to add new functions to existing classes without modifying them or using inheritance. This makes our code more readable, reusable, and clean.What is an Extension Function?An extension function is a function that is defined
4 min read
Kotlin genericsGenerics are one of Kotlin's most powerful features. They allow us to write flexible, reusable, and type-safe code. With generics, we can define classes, methods, and properties that work with different types while still maintaining compile-time type safety.What Are Generics?A generic type is a clas
6 min read
Exception Handling
Kotlin Exception Handling - try, catch, throw and finallyException handling is an important part of programming that helps us manage errors in our code without crashing the entire application. In this article, we will learn about exception handling in Kotlin, how to use try, catch, throw, and finally blocks, and understand different types of exceptions.Ko
5 min read
Kotlin Nested try block and multiple catch blockIn Kotlin, exception handling allows developers to manage errors gracefully and prevent application crashes. In this article, we will explore two advanced exception handling concepts in Kotlin:Nested try-catch blocksMultiple catch blocks, including how to simplify them using a when expression.Nested
3 min read
Null Safety