Function call in object

I am trying to understand the code snippet below(removed some not relevant bits).
When ‘status’ is called, why is ‘toString(): String’ function called too? What calls it?

data class ParkingLot(val size: Int) {
    data class Car(val plate: String, val color: String) {
        override fun toString() = "$plate $color"
    }

    data class Spot(val spotNumber: Int, val isFree: Boolean, val car: Car?) {
        override fun toString() = "$spotNumber $car"
    }

    private val parkingData = Array(size) { Spot(it + 1, true, null) }

    init {
        if (size != 0) println("Created a parking lot with $size spots.")
    }

    override fun toString(): String {
        val str = parkingData.filter { !it.isFree }.joinToString("\n") { it.toString() }
        return when {
            size == 0 -> "Sorry, a parking lot has not been created."
            str.isEmpty() -> "Parking lot is empty."
            else -> str
        }
    }
}

fun main() {
    var parkingLot = ParkingLot(0)
    while (true) {
        val command = readLine()!!.split(" ")
        when (command[0]) {
            "create" -> parkingLot = ParkingLot(command[1].toInt())
            //"park" -> parkingLot.park(ParkingLot.Car(command[1], command[2]))
            //"leave" -> parkingLot.leave(command[1].toInt())
            "status" -> println(parkingLot)
            "exit" -> return
        }
    }
}

println internally calls toString to turn your object to a string that can be then printed

2 Likes