Home > Mobile >  Kotlin function for data class
Kotlin function for data class

Time:07-28

What is the best way in Kotlin to write a function that can be used by a data class?

For example, say I have a data class and I need a function where the result is based on the value of a field from that data class:

data class Person(
  val dateOfBirth: String
)

How would I go about writing an 'age' function for the Person object?

CodePudding user response:

The same way you would write it for a non-data class!

You could add a method within the class:

data class Person(val dateOfBirth: String) {
    fun age() = // …
}

Or you could add an extension method outside it:

data class Person(val dateOfBirth: String)

fun Person.age() = //…

(A method within the class is usually a better option if you can modify the class, and it belongs conceptually to the class. An extension method is useful if you don't have access to the class, or if it's specific to some particular usage or has a dependency on something unrelated to the class.)

Of course, you can always write a simple, old-style function:

fun calculateAge(person: Person) = // …

…but an extension method is clearer, reads better, and your IDE will suggest it.


In this case (where the age is quick to calculate, doesn't change the object's visible state, and won't throw an exception), a property or extension property might be more natural:

data class Person(val dateOfBirth: String) {
    val age get() = // …
}

Or:

data class Person(val dateOfBirth: String)

val Person.age get() = //…

Then you can access it simply as myPerson.age.

CodePudding user response:

The same way you would for any other class:

data class Person(val dateOfBirth: String) {

    fun age(): Int {
        // Use dateOfBirth here to compute the age.
    }
}
  • Related