Search code examples
androidkotlincastingadapter

Cast a specific object to another


I'm trying to cast one object to another, that are the same(same attributes) but I keep getting that I can't do this cast. I have these two objects, and one adapter that uses PatientFile as the main object but I want to use i for DoctorFile too because is the same object, but when I try to cast it, it just keep showing the cast cannot be succeded.

So my question is how can I cast the object DoctorFile to PatientFile that are the same object and use it in my adapter as a list. And if you ask I can't create only one object because these 2 are received from a petition from retrofit.

Object 1:

 data class DoctorFiles(
   val file: String,
   val id: String,
   val name: String
): Serializable

Object 2:

 data class PatientFiles(
   val file: String,
   val id: String,
   val name: String
): Serializable

Adapter:

class ConsultationDocumentsAdapter(private val onDownload: (PatientFilesId)->Unit):RecyclerView.Adapter<ConsultationDocumentsHolder>() {
private var list: List<PatientFilesId> = listOf()

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConsultationDocumentsHolder {
    val inflater = LayoutInflater.from(parent.context)
    return ConsultationDocumentsHolder(inflater, parent, onDownload)
}

override fun onBindViewHolder(holder: ConsultationDocumentsHolder, position: Int) {
    holder.bind(list[position])
}

override fun getItemCount(): Int = list.size

fun loadItems(documents: List<PatientFilesId>) {
    list = documents
    notifyDataSetChanged()
}

}

class ConsultationDocumentsHolder(
  inflater: LayoutInflater,
 parent: ViewGroup,
 private val onDownload: (PatientFilesId) -> Unit
 ) :
   RecyclerView.ViewHolder(inflater.inflate(R.layout.cell_consultation_documents, 
parent, false)) {

private lateinit var documentName: TeladocTextView
private lateinit var documentSize: TeladocTextView
private lateinit var documentDownload: AppCompatImageView

fun bind(document: PatientFilesId) {
    setupUi()
    loadConsultationDocumentData(document)
}

private fun setupUi() {
    documentName = itemView.findViewById(R.id.consultation_document_name)
    documentSize = itemView.findViewById(R.id.consultation_document_size)
    documentDownload = itemView.findViewById(R.id.consultation_document_download)
}

private fun loadConsultationDocumentData(document: PatientFilesId) {
    documentName.text = document.name
    val size = "" + TeladocUtils.sizeOfFile(document.file) / 1024
    documentSize.text = size + "Mb"

    documentDownload.setOnClickListener{
        onDownload(document)
    }
}

}

Solution

  • You can't cast them I'm afraid. Even if they have the same properties, a DoctorFile isn't a PatientFile.

    What would be sensible is to set up an inheritance structure, so both PatientFile and DoctorFile inherit from a File with the relevant properties, or simply copy the properties into a new object.