Utilities
Utilities
We can create singleton to group related utility functions into a single entity. Suppose we define multiple functions related to calendar :
isLeapYear(year: Int): Boolean
getNoOfDaysInMonth(month: Int, year: Int): Int
getNoOfDaysBetween(start: Date, end: Date): Int
Instead of defining them directly in a file, we can define them in a singleton called CalendarUtils
:
object CalendarUtils {
fun isLeapYear(year: Int): Boolean { TODO() }
fun getNoOfDaysInMonth(month: Int, year: Int): Int { TODO() }
fun getNoOfDaysBetween(start: Date, end: Date): Int { TODO() }
}
We can directly access this functions using the singleton name :
object CalendarUtils {
fun isLeapYear(year: Int): Boolean { TODO() }
fun getNoOfDaysInMonth(month: Int, year: Int): Int { TODO() }
fun getNoOfDaysBetween(start: Date, end: Date): Int { TODO() }
}
fun main() {
val is2020ALeapYear = CalendarUtils.isLeapYear(2020)
val noOfDaysInFeb2023 = CalendarUtils.getNoOfDaysInMonth(2, 2023)
}
Constants
Constants
We can create singleton to group multiple constants. Constant is a variable with fixed value used all across an application. For example, in a game we may have constants like
- maximum lifelines,
- total number of levels,
- maximum number of players etc.
We can define them in a singleton called Constants :
object Constants {
const val MAX_LIFELINES = 20
const val TOTAL_LEVELS = 100
const val MAX_PLAYERS = 6
}
We can access them directly as :
if (level == Constants.TOTAL_LEVELS) {
println("Congratulations, you have completed the game!")
}
Note :
- Singletons don’t have constructors. They are constructed as soon as the program runs and reside in memory till the end.
- Like normal classes, singetons can also inherit from open classes.
- Singletons can’t be declared as
open
i.e. they can’t be inherited.