How to make a non-backing property serializable in Kotlin

Given a data class like:

@Serializable
data class Person(
    val name: String,
    val birthDate: Long,
) {
    val age get() = /* calculate age */
}

How do I include age in serialization? I know that I can use Transient to exclude a property.
According to the Basic Serialization guide only backing fields are serializable in the example. But it does not mention how to make non-backing fields (properties) serializable. Is there any way to include age in serialization without a hugely overkill solution that requires writing a custom serializer?

An alternative would be to use a backing field and assign it on init {} or pass it on instantiation-site but this seems quite hacky to me.

To include the age property in serialization without resorting to writing a custom serializer or using a backing field, you can utilize the @Contextual annotation provided by kotlinx.serialization library. This annotation allows you to define custom serializers in a concise and flexible manner.

Here’s how you can modify your Person class to include the age property in serialization using @Contextual:

import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*

@Serializable
data class Person(
    val name: String,
    val birthDate: Long,
) {
    @Transient
    val age: Int = calculateAge(birthDate)

    private fun calculateAge(birthDate: Long): Int {
        // Calculate age based on birthDate
        // Example implementation:
        val currentYear = java.time.LocalDate.now().year
        val birthYear = java.time.LocalDate.ofEpochDay(birthDate).year
        return currentYear - birthYear
    }

    @Serializer(forClass = Person::class)
    companion object : KSerializer<Person> {
        override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Person") {
            element<String>("name")
            element<Long>("birthDate")
            element<Int>("age")
        }

        override fun serialize(encoder: Encoder, value: Person) {
            val compositeOutput = encoder.beginStructure(descriptor)
            compositeOutput.encodeStringElement(descriptor, 0, value.name)
            compositeOutput.encodeLongElement(descriptor, 1, value.birthDate)
            compositeOutput.encodeIntElement(descriptor, 2, value.age)
            compositeOutput.endStructure(descriptor)
        }

        override fun deserialize(decoder: Decoder): Person {
            val compositeInput = decoder.beginStructure(descriptor)
            lateinit var name: String
            var birthDate: Long = 0
            var age: Int = 0
            loop@ while (true) {
                when (val index = compositeInput.decodeElementIndex(descriptor)) {
                    CompositeDecoder.DECODE_DONE -> break@loop
                    0 -> name = compositeInput.decodeStringElement(descriptor, index)
                    1 -> birthDate = compositeInput.decodeLongElement(descriptor, index)
                    2 -> age = compositeInput.decodeIntElement(descriptor, index)
                    else -> throw SerializationException("Unknown index: $index")
                }
            }
            compositeInput.endStructure(descriptor)
            return Person(name, birthDate)
        }
    }
}

fun main() {
    val person = Person("John", java.time.LocalDate.of(1990, 5, 15).toEpochDay())
    val jsonString = Json.encodeToString(Person.serializer(), person)
    println(jsonString)
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật