1. KClass and ::class: Getting Started with Reflection

[THEORY]

[PREDICT]

Read the code carefully before you run it.

prediction.kt
open class Vehicle(val licensePlate: String)
class DeliveryVan(licensePlate: String, val payload: Int) : Vehicle(licensePlate)

fun describe(vehicle: Vehicle) {
    println(vehicle::class.simpleName)
}

fun main() {
    val fleet: List<Vehicle> = listOf(
        Vehicle("B-AB 123"),
        DeliveryVan("B-CD 456", 500)
    )
    fleet.forEach { describe(it) }
}

describe() takes a Vehicle. Does it print "Vehicle" for both list elements, or does the output differ?

[TASK]

A warehouse management system should log which class it is dealing with for any object. Write a function className(obj: Any): String that returns the simpleName of the actual class of obj — or "Unknown" if simpleName is null (can happen with anonymous objects). Call it in main() for a Product and an SparePart.

task.kt
open class Product(val name: String, val price: Double) class SparePart(name: String, price: Double, val serialNumber: String) : Product(name, price) // TODO: fun className(obj: Any): String fun main() { val product: Product = Product("Screwdriver", 4.99) val sparePart: Product = SparePart("Gear", 12.50, "ZR-2201") // TODO: println(className(product)) // TODO: println(className(sparePart)) }

Before you get a hint: what have you tried, and where exactly are you stuck?

[COMPREHENSION CHECK]

1. What does instance::class return when instance is declared as the type BaseClass but actually holds a subclass?

2. Which additional library do you need to use most KClass features (for example memberProperties, which appears in a later lesson) at runtime?

3. What does Customer::class.java return?