https://kotlinlang.org logo
#getting-started
Title
# getting-started
b

Bernhard

11/15/2021, 2:52 PM
Hi, I've got a data class but in one case I want one attribute of it to be evaluated again on each access (getting the current date basically). How do I do this?
m

Michael de Kaste

11/15/2021, 2:59 PM
custom getter basically. However, the whole purpose of it being a data class will be null and void.
Copy code
data class SomeClass(
    val someField: String,
    val someOtherField: Int
) {
    val currentDate: LocalDate
        get() = LocalDate.now()
}
this is what you can do
b

Bernhard

11/15/2021, 3:01 PM
can I decide that in the constructor without making each property a lambda?
SomeClass(currentDate by x { Date() })
basically I'd like to define the getter in the constructor
because in most cases a static value is just fine, it's just that one exception
don't want to create a separate class for that
m

Michael de Kaste

11/15/2021, 3:07 PM
you can put the delegation in your constructor, but never specify how a field is backed in the constructor itself.
Why does it NEED to be in a constructor?
1
b

Bernhard

11/15/2021, 3:10 PM
because I want to configure it by case basis
usecase here is a download object where in one case I need to set the url parameter to be the current date time stamp
p

Paul Griffith

11/15/2021, 3:25 PM
sealed class DownloadObject
data class NormalCase : DownloadObject()
class SpecialCase : DownloadObject()