In this article, we will continue to develop the previous book price calculator by introducing the custom getter and setter method which will help us to set the sale taxes and to return the total price amount to the main program.

Below lines of new code will create the setter and the getter method within a singleton object that will then be used for the above purposes!

object FilterBook {

    var total_price : Double = 0.00
    var sale_tax : Double = 0.00

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

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

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

    fun print_total() {

    var total_amount : String
        get() {
            return "%.2f".format(total_price)

    set(value) {
        sale_tax = value.toDouble()

As you can see we will no longer need to call the print total function but instead will use the getter method to return the total amount to the caller in the main program.

fun main(args : Array<String>) {
    FilterBook.sale_tax = 1.029
    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))

    print(FilterBook.total_amount) // output 72.03

The getter and setter method is the read and writes property that we will often see within a Kotlin class.

This article is only showing you how to use the getter and setter property within the Kotlin class. Of course, we do not even need to create the singleton object when dealing with such a simple example besides using this object to demonstrate to the reader the use of the above methods.

Please follow and like us:

Leave a Reply

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