How to Implement Offline Caching using NetworkBoundResource in Android?
Last Updated :
23 Jul, 2025
Almost, every android application that requires fetching data over a network, needs caching. First, let understand What does caching means? Most of us have used applications that require the data to be fetched from the web. Such an application with an offline-first architecture will always try to fetch the data from the local storage. On the other hand, if there is some failure, it requests the data to be fetched from a network, thereafter storing it locally, for future retrieval. The data will be stored in an SQLite database. The advantage of such an architecture is that we will be able to use the application even if it is offline. Moreover, since the data is cached, the application will respond faster. To handle caching, we will be using NetworkBound Resource. It is a helper class that decides when to use the cache data and when to fetch data from the web and update the View. It coordinates between the two.

The above decision tree shows the algorithm for the NetworkBound Resource algorithm.
The Algorithm
Let us see the flow of this algorithm:
- Whenever the user accesses the application in offline mode, the data is dispatched into the view, it can either be a fragment or an activity.
- If there is no data or the data is insufficient in the disk as a cache, then it should fetch the data over the network.
- It checks if there is a need to log in (if the user logouts, then re-login would be required). It re-authenticates, if successful then it fetches the data, but it failed, then it prompts the user to re-authenticate.
- Once the credentials are matched, then it fetches the data over the network.
- If the fetch phase is failed, then it prompts the user.
- Otherwise, if successful, then the data is stored automatically into the local storage. It then refreshes the view.
The requirement here is, there should be minimal changes in the User Experience when the user comes to online mode. So process like Re-authentication, fetching data over the network, and refreshing the views should be done in the background. One thing to be noted here is, the user only needs to re-login, if there are some changes in the user credentials like password, or username.
Implementation
To understand more about this, let us build an application. This is a simple news application, which uses a fake API for fetching data from the web. Let us look at the high-level design of our application:
- It will be using MVVM architecture.
- SQLite database for caching data.
- Use Kotlin FLow.(Kotlin Coroutine)
- Dagger Hilt for dependency injection.

The above diagram is the overview of the architecture that will be implemented in our application. This architecture is recommended by Android to develop a modern well-architecture android application. Let us start building the project.
Step by Step Implementation
Step 1: Create a New Project
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: Setting up the layout
It is always recommended to first set up the layout, followed by implementing the logic. So we will first create the layout. As mentioned, we will be fetching data from a web service. Since this is a sample project, we would just fetch data from a random data generator. Now the data is a list of cars, which would include the following properties:
- Make and model of car
- Transmission of the car
- Colour of the car
- Drive type of the car.
- Fuel type of the car.
- Car type of the car.
We will be using RecyclerView to show the list. Hence first it is required to design how each element of the list would look like. Followed by making the list.
XML
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
android:layout_margin="4dp">
<!-- This will display the make and model of the car-->
<TextView
android:id="@+id/car_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:textColor="@color/black"
android:textSize="15sp"
tools:text="Car Name" />
<!-- This will display the transmission type of the car-->
<TextView
android:id="@+id/car_transmission"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_toEndOf="@id/car_name"
tools:text="Transmission type" />
<!-- This will display the colour of the car-->
<TextView
android:id="@+id/car_color"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/car_name"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
tools:text="Car colour" />
<!-- This will display the drive type of the car-->
<TextView
android:id="@+id/car_drive_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/car_name"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_toEndOf="@id/car_color"
tools:text="Car Drive Type" />
<!-- This will display the fuel type of the car-->
<TextView
android:id="@+id/car_fuel_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/car_transmission"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_toEndOf="@id/car_drive_type"
tools:text="Car fuel_type" />
<!-- This will display the car type of the car-->
<TextView
android:id="@+id/car_car_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/car_transmission"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_toEndOf="@id/car_fuel_type"
tools:text="Car Type" />
</RelativeLayout>
Now, let's code the list layout:
XML
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".CarActivity">
<!-- The recycler view-->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_viewer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:padding="4dp"
tools:listitem="@layout/carlist_item" />
<!--Initially the app will fetch data from the
web, hence a progress bar for that-->
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="invisible"
tools:visibility="visible" />
<!--If the application is not able to
fetch/ expose the data to the view-->
<TextView
android:id="@+id/text_view_error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="8dp"
android:gravity="center_horizontal"
android:visibility="invisible"
tools:text="Error Message"
tools:visibility="visible" />
</RelativeLayout>
Step 3: Now let's create the API package
CarListAPI.kt
Kotlin
package com.gfg.carlist.api
import com.gfg.carlist.data.CarList
import retrofit2.http.GET
interface CarListAPI {
// Companion object to hold the base URL
companion object{
const val BASE_URL = "https://random-data-api.com/api/"
}
// The number of cars can be varied using the size.
// By default it is kept at 20, but can be tweaked.
// @GET annotation to make a GET request.
@GET("vehicle/random_vehicle?size=20")
// Store the data in a list.
suspend fun getCarList() : List<CarList>
}
Step 4: Implementing the app module
A module is nothing but an object class, which provides a container to the app's source code. It encapsulates data models associated with a task. The android architecture suggests making minimal use of business logic in the view model, hence the business application task is represented in the app module. It will include three methods:
- A method for calling the API via Retrofit
- A method to provide the list
- A method to provide the database or rather build a database.
AppModule.kt
Kotlin
package com.gfg.carlist.di
import android.app.Application
import androidx.room.Room
import com.gfg.carlist.api.CarListAPI
import com.gfg.carlist.data.CarListDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideRetrofit(): Retrofit =
Retrofit.Builder()
.baseUrl(CarListAPI.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
@Provides
@Singleton
fun provideCarListAPI(retrofit: Retrofit): CarListAPI =
retrofit.create(CarListAPI::class.java)
@Provides
@Singleton
fun provideDatabase(app: Application): CarListDatabase =
Room.databaseBuilder(app, CarListDatabase::class.java, "carlist_database")
.build()
}
Step 5: Creating Data Class
We are done with handling the API, fetching the data from the web service, but where to store the data? Let's create a class to store the data. We have to create a data class. If the app were to just fetch and expose data, then it would have just a single data class file. But here, we have to fetch, expose as well as cache the data. Hence ROOM comes into play here. So in the data class, we've to create an entity.
CarList.kt
Kotlin
package com.gfg.carlist.data
import androidx.room.Entity
import androidx.room.PrimaryKey
// Data Class to store the data
// Here the name of the table is "cars"
@Entity(tableName = "cars")
data class CarList(
@PrimaryKey val make_and_model: String,
val color: String,
val transmission: String,
val drive_type: String,
val fuel_type: String,
val car_type: String
)
Since we would be caching the data locally, hence a database is needed to be created.
CarListDatabase.kt
Kotlin
package com.gfg.carlist.data
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [CarList::class], version = 1)
abstract class CarListDatabase : RoomDatabase() {
abstract fun carsDao(): CarsDao
}
Since we have created a table, we need to have some queries to retrieve data from the table. This is achieved using DAO or Data Access Object.
CarsDao.kt
Kotlin
package com.gfg.carlist.data
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface CarsDao {
// Query to fetch all the data from the
// SQLite database
// No need of suspend method here
@Query("SELECT * FROM cars")
// Kotlin flow is an asynchronous stream of values
fun getAllCars(): Flow<List<CarList>>
// If a new data is inserted with same primary key
// It will get replaced by the previous one
// This ensures that there is always a latest
// data in the database
@Insert(onConflict = OnConflictStrategy.REPLACE)
// The fetching of data should NOT be done on the
// Main thread. Hence coroutine is used
// If it is executing on one one thread, it may suspend
// its execution there, and resume in another one
suspend fun insertCars(cars: List<CarList>)
// Once the device comes online, the cached data
// need to be replaced, i.e. delete it
// Again it will use coroutine to achieve this task
@Query("DELETE FROM cars")
suspend fun deleteAllCars()
}
A repository class to handle data from web service and the data locally.
CarListRepository.kt
Kotlin
package com.gfg.carlist.data
import androidx.room.withTransaction
import com.gfg.carlist.api.CarListAPI
import com.gfg.carlist.util.networkBoundResource
import kotlinx.coroutines.delay
import javax.inject.Inject
class CarListRepository @Inject constructor(
private val api: CarListAPI,
private val db: CarListDatabase
) {
private val carsDao = db.carsDao()
fun getCars() = networkBoundResource(
// Query to return the list of all cars
query = {
carsDao.getAllCars()
},
// Just for testing purpose,
// a delay of 2 second is set.
fetch = {
delay(2000)
api.getCarList()
},
// Save the results in the table.
// If data exists, then delete it
// and then store.
saveFetchResult = { CarList ->
db.withTransaction {
carsDao.deleteAllCars()
carsDao.insertCars(CarList)
}
}
)
}
Step 6: Working on the UI
Remember in Step 1, we created a RecyclerView to expose the list of cars. But the work is not completed till now. We need to make an adapter as well as a ViewModel. These two classes work together to define how our data is displayed.
CarAdapter.kt
Kotlin
package com.gfg.carlist.features.carlist
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.gfg.carlist.data.CarList
import com.gfg.carlist.databinding.CarlistItemBinding
class CarAdapter : ListAdapter<CarList, CarAdapter.CarViewHolder>(CarListComparator()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarViewHolder {
val binding =
CarlistItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return CarViewHolder(binding)
}
override fun onBindViewHolder(holder: CarViewHolder, position: Int) {
val currentItem = getItem(position)
if (currentItem != null) {
holder.bind(currentItem)
}
}
// View Holder class to hold the view
class CarViewHolder(private val binding: CarlistItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(carlist: CarList) {
binding.apply {
carName.text = carlist.make_and_model
carTransmission.text = carlist.transmission
carColor.text = carlist.color
carDriveType.text = carlist.drive_type
carFuelType.text = carlist.fuel_type
carCarType.text = carlist.car_type
}
}
}
// Comparator class to check for the changes made.
// If there are no changes then no need to do anything.
class CarListComparator : DiffUtil.ItemCallback<CarList>() {
override fun areItemsTheSame(oldItem: CarList, newItem: CarList) =
oldItem.make_and_model == newItem.make_and_model
override fun areContentsTheSame(oldItem: CarList, newItem: CarList) =
oldItem == newItem
}
}
CarListViewModel.kt
Kotlin
package com.gfg.carlist.features.carlist
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import com.gfg.carlist.data.CarListRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
// Using Dagger Hilt library to
// inject the data into the view model
@HiltViewModel
class CarListViewModel @Inject constructor(
repository: CarListRepository
) : ViewModel() {
val cars = repository.getCars().asLiveData()
}
Finally, we have to create an activity to show the data from the ViewModel. Remember, all the business logic should be present in the ViewModel, and not in the activity. The activity should also not hold the data, because when the screen is tilted, the data gets destroyed, due to which the loading time increases. Hence the purpose of the activity is to only show the data.
CarActivity.kt
Kotlin
package com.gfg.carlist.features.carlist
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.gfg.carlist.databinding.ActivityCarBinding
import com.gfg.carlist.util.Resource
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class CarActivity : AppCompatActivity() {
// Helps to preserve the view
// If the app is closed, then after
// reopening it the app will open
// in a state in which it was closed
// DaggerHilt will inject the view-model for us
private val viewModel: CarListViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// The below segment would
// instantiate the activity_car layout
// and will create a property for different
// views inside it!
val binding = ActivityCarBinding.inflate(layoutInflater)
setContentView(binding.root)
val carAdapter = CarAdapter()
binding.apply {
recyclerViewer.apply {
adapter = carAdapter
layoutManager = LinearLayoutManager(this@CarActivity)
}
viewModel.cars.observe(this@CarActivity) { result ->
carAdapter.submitList(result.data)
progressBar.isVisible = result is Resource.Loading<*> && result.data.isNullOrEmpty()
textViewError.isVisible = result is Resource.Error<*> && result.data.isNullOrEmpty()
textViewError.text = result.error?.localizedMessage
}
}
}
}
Finally, we are done with the coding part. After successfully building the project, the app would look like this:
Output:

The following video demonstrates the application.
Output Explanation:
Project Link: Click Here
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