Kotlin properties used in Android RecyclerView


#1

This might actually be a design question not specific to Android.

I have a kotlin data class that I use to populate a listitem in a RecyclerView. I’ve added some extra properties to the class using the following code:

data class WorklistItem(
                        val id: String,
                        val name: String,
                        val birthDate: String,
                        val page: Int) {

    val firstname : String
        get() { return patientName.split("^").last() }
    val lastName : String
        get() { return patientName.split("^").first() }
    val fullName : String
        get() { return "$firstname $lastName" }
}

I was wondering though, why doesn’t this work (this displays the extra propertyvalues as null):

data class WorklistItem(
                        val id: String,
                        val name: String,
                        val birthDate: String,
                        val page: Int) {

    val firstname = name.split("^").last()
    val lastName = name.split("^").first() }
    val fullName = "$firstname $lastName"
}

#2

It’s working fine here.
If what you want is for your extra properties to show on toString() you need to put them on the constructor.
Like:

data class Item(
	val name: String,
	val firstname: String = name.split("^").last(),
	val lastName: String = name.split("^").first(),
	val fullName: String = "$firstname $lastName"
)
fun main(args: Array<String>) {
	println(Item("Foo^Bar"))
}