Convention allows a programmer to use a function with an operator, for example, we can use a plus sign to invoke the plusAssign method in the custom Kotlin class to perform a certain operation!

In this chapter, we will continue to develop our student bookkeeping application by introducing the total amount class which has the plusAssign function which we have talked about above that will perform the sum-up operation of the total Kotlin’s books purchased by all the students.

class TotalAmount {
    var total : Double = 0.00
    operator fun plusAssign(student : Stdent1) {
        total += student.total_purchase

    fun total_purchasing() {
        println("Total Purchase From All Students:") // header
        print("%.2f".format(total)) // output 926.10

As you can see, we have moved the print out’s process from the main file to this Kotlin class (please refer to the previous chapter). In order to use the convention method as an operator, we need to include the keyword “operator” in front of the plusAssign method.

Now we also need to amend the student group interface to suit the new condition.

interface StudentGroup<T> {
    fun PrintTotalAmount()
    fun AddPurchasedTotal(student : T)

We can then start to amend those methods within the student grouping class to suit the new changes.

class StdentGrouping : StudentGroup<Stdent1> {
    val total_amount = TotalAmount()

    // print out total amount of books
    override fun PrintTotalAmount() {

    override fun AddPurchasedTotal(student : Stdent1) {
        total_amount += student //Add student total purchased to the total amount


If you refer to the previous chapter you will notice that the list object has been omitted from the above class because we will use the plusAssign method in the Total Amount class to directly sum-up the total student purchased amount instead.

Finally, we will amend the main file accordingly to print out the total purchased amount for all the students.

fun main(args : Array<String>) {

    FilterBook.sale_tax = 1.029
    val student_group = StdentGrouping()

    val reader = Reader("src/count.txt") // initialize the java reader class
    val count = reader.student_count // the total student
    for(total_student in (1..count))
    student_group.PrintTotalAmount() // print total amount of books purchased by the student

The program above will yield the same result as the previous one.

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

Leave a Reply

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