Constructors and Properties

Classes, Constructors and Properties

A Kotlin class puts its primary constructor in the header. A parameter marked val or var becomes a property; an unmarked parameter is only an argument, visible to property initializers and init blocks. There is no new.

A cart line with a validated setter and a computed property (classes.kt)Kotlin
class CartLine(val title: String, unitPrice: Double, quantity: Int = 1) {
  var quantity: Int = quantity
    set(value) {
      require(value >= 0) { "quantity must be >= 0" }
      field = value
    }
  private val unitCents = Math.round(unitPrice * 100)
  val totalCents: Long get() = unitCents * quantity
}
fun main() {
  val line = CartLine("The Quiet Harbor", 14.99)
  line.quantity = 3
  println("${line.title}: ${line.totalCents / 100.0}")
  println(CartLine("Gardens in Glass", 21.30, -5).quantity)
  line.quantity = -1
}
Output
The Quiet Harbor: 44.97
-5
Exception in thread "main" java.lang.IllegalArgumentException: quantity must be >= 0
    at CartLine.setQuantity(classes.kt:4)
...

A property is a private field plus accessors, hence CartLine.setQuantity in the trace. Inside an accessor, field is the backing field (assigning quantity there would recurse). totalCents has no field and is recomputed on each read. line.unitPrice fails with unresolved reference 'unitPrice'.

The -5 is a real bug: the initializer writes the field directly, bypassing the setter, so validate in an init block too. Default arguments (Function Declarations) replace most secondary constructors.