Lesson contents

Kotlin — Data classes and member functions

A Kotlin data class keeps related constructor properties together. A member function can calculate the subtotal from quantity and unit price.

A simple example

Read one field

  1. Start with A point with x = 2
  2. Do this Read x
  3. Result 2
A record keeps related values together. Here the program reads a single named field.
Lesson.kt
data class Point(val x: Int)
fun main() {
    println(Point(2).x)
}
Output
2
Advertisements

Represent an invoice line

The primary constructor exposes immutable properties through val. A data class generates structural equality and copy. The method computes its result using those properties.

One line item: 3 juices. Price per juice: 125¢. Subtotal: 375¢.
Keep an invoice line together

A café invoice lists three juices at 125 cents each. Store the quantity and price together, then calculate the subtotal when the receipt is printed. Changing the quantity can then update the total automatically.

Run the example

Kotlin/JVM. Run these commands from the directory containing the example.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Lesson.kt
data class LineItem(val units: Int, val cents: Int) {
    fun subtotal(): Int = units * cents
}

fun main() {
    val line = LineItem(units = 3, cents = 125)
    println(line.subtotal())
}
Output
375

The line holds three units at 125 cents each. Multiplication gives 375 cents. Keeping the subtotal derived means there is no third field that can become stale.

Try it yourself

Create a second line with two units at 90 cents each.

Check your answer

Its subtotal is 180 cents. The two subtotals together are 555 cents before any taxes or delivery charges.

Kotlin language documentation

Related tags

  • Kotlin
  • data modeling
  • records
  • methods