A singleton object will not allow you to create an instance from it,
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 { it.key.contains("Kotlin") } kotlin_book_list.forEach{ total_price += it.value * sale_tax // include 2.9 % sale taxes } } fun print_total() { print("%.2f".format(total_price)) } 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
tҺe website іѕ really good, I love your blog!