In the previous article, we have created the FilterBook object to calculate the total price for the Kotlin programming language related books. In this chapter, we will create a singleton object instead to perform the above calculation. Singleton object is the object which only has one instance which can be used just like the Java static class in the Kotlin program.

First, we will create the singleton object with the object keyword in front of that object name.

object FilterBook {
    var total_price : Double = 0.00

    fun calculate_total_price(book: Map<String, Double>) {

        var kotlin_book_list : Map<String, Double> = book.filter {

            total_price += it.value * 1.029 // include 2.9 % sale taxes

    fun print_total() {

Next we will create the main program and use the singleton object to calculate and print out the total amount.

fun main(args : Array<String>) {
    FilterBook.calculate_total_price(book = mapOf("Kotlin" to 20.00, "Kotlin is really great" to 10.00, "Other Program" to 26.00, "Why Kotlin is really great" to 40.00))
    FilterBook.print_total() // output 72.03

Singleton is very popular among the Kotlin programmer and unless it is necessary to create the Kotlin class we should stick to the Singleton object instead.

In the previous article, I have mentioned before that I want to create a Kotlin’s desktop application, however, due to lack of Kotlin user interface framework I have given up the original plan, instead, I will start to write a new android application with Kotlin beginning from the next chapter onwards, so do subscribe to the Kotlin rss feed from this website if you want to read more about this project or just bookmarked this website for the future visit!

Please follow and like us:

1 Comment

  1. This is plain wrong use of singleton! You hold a global variable inside object that accumulates prices on every method call!

Leave a Reply

Your email address will not be published. Required fields are marked *