How to declare, initialize, and print a medium complexity, varied, feature‑rich data structure in Kotlin

1 Answer

0 votes
import java.time.LocalDate

data class Address(
    var street: String = "",
    var city: String = "",
    var zip: Int = 0
)

enum class Status {
    Active, Inactive, Unknown
}

data class Person(
    var homeAddress: Address = Address(),
    var favoriteNumbers: List<Int> = List(5) { 0 },
    var nickname: String? = null,
    var birthDate: LocalDate = LocalDate.of(1990, 1, 1),
    var notes: String = "No notes",
    var middleName: String? = null,
    var hobbies: List<String> = emptyList(),
    var status: Status = Status.Unknown
)

fun printPerson(p: Person) {
    println("Address: ${p.homeAddress.street}, ${p.homeAddress.city} ${p.homeAddress.zip}")

    println("Favorite Numbers: ${p.favoriteNumbers.joinToString(" ")}")

    println("Nickname: ${p.nickname ?: "(none)"}")

    println("Birth Date: ${p.birthDate}")

    println("Notes: ${p.notes}")

    println("Middle Name: ${p.middleName ?: "(none)"}")

    val hobbiesText =
        if (p.hobbies.isNotEmpty()) p.hobbies.joinToString(", ") + ", "
        else "(none)"
    println("Hobbies: $hobbiesText")

    println("Status: ${p.status}")
}

fun main() {
    val p = Person(
        homeAddress = Address("Fifth Avenue", "New York", 423900),
        favoriteNumbers = listOf(7, 13, 21, 42, 99),
        nickname = "Orion",
        birthDate = LocalDate.of(1026, 6, 15),
        notes = "Voss likes C/C++ and structs",
        middleName = "Pulse-9",
        hobbies = listOf("Coding", "Dreaming", "Walking", "Sci-Fi Movies"),
        status = Status.Active
    )

    printPerson(p)
}


/*
run:

Address: Fifth Avenue, New York 423900
Favorite Numbers: 7 13 21 42 99
Nickname: Orion
Birth Date: 1026-06-15
Notes: Voss likes C/C++ and structs
Middle Name: Pulse-9
Hobbies: Coding, Dreaming, Walking, Sci-Fi Movies, 
Status: Active

*/

 



answered Sep 3 by avibootz

Related questions

...