A singleton object will not allow you to create an instance from it, singleton is often used by the Kotlin programmer as a single object to perform all the works. Class inheritance, on the other hand, allows the user to create a subclass from the parent class, that subclass will have all the properties of that parent class plus its own properties.

In this example, we will create a singleton object used to calculate the total purchase price of those books that are only related to the Kotlin programming topic. We then create the subclass from the student class and pass in the total book purchases for each student as the parameter to the subclass. Finally, we sum up the total purchase amount from each student to get the total purchases of the books that are related to Kotlin programming topic.

Create the singleton object.

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_purchase : Double
         get() {
             return total_price

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

Create the parent class for all the students.

open class Student(var amount : Double) {
    val total_purchase : Double
        get() {
            return amount

Most of the classes in Kotlin are the final class which means no inheritance is allowed unless there is the open keyword in front of that class which means that class will be allowed to be subclassed if we really need to.

Create the subclass from the above Student class.

class Stdent1(total : Double) : Student(total)

We will further include more features into the above subclass but at the moment let us go to the final part of the 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))
    val jimmy = Stdent1(FilterBook.total_purchase)
    val tommy = Stdent1(FilterBook.total_purchase)
    val george = Stdent1(FilterBook.total_purchase)
    print(jimmy.total_purchase + tommy.total_purchase + george.total_purchase) // output 216.09

In the above main program, we will print out the total book’s purchase amount from all those students.

You might ask me why are we not using the for loop to calculate the total purchase prices instead of going through all those troubles? Well, because Kotlin is an OOP type of programming language, which is also the main reason why you are learning Kotlin for.

Click to rate this post!
[Total: 0 Average: 0]
Please follow and like us:

1 Comment

Leave a Reply

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