Search code examples
kotlindata-classcompanion-object

How do I get context inside a companion object that is inside a data class Kotlin?


I'm trying to use a resource string inside a companion object that is inside a data class. but I don't Know how to obtain context in that case in Kotlin. Anyone knows how to do it?

data class PhoneCall(
val type: String,
    val code: String,
    val description: String){
companion object{
const val SOLUTION_NO_SOLUTION = "NO_SOLUTION" 
        const val SOLUTION_TOMORROW = "71_INAT"
        const val SOLUTION_TODAY = "72_INAT"

val solutions = listOf(
PhoneCall(Service.Traffic.PICK_UP, SOLUTION_NO_SOLUTION, Resources.getSystem().getString(R.string.makeService))
)
}

I need to use a resource string in the 3 parameter, but I'm not able to get the context.


Solution

  • You can modify you PhoneCall model to store a string resource id instead of the actual string.

    data class PhoneCall(
        val type: String,
        val code: String,
        @StringRes val description: Int
    ) {
        companion object {
            const val SOLUTION_NO_SOLUTION = "NO_SOLUTION" 
            const val SOLUTION_TOMORROW = "71_INAT"
            const val SOLUTION_TODAY = "72_INAT"
    
            val solutions = listOf(
                PhoneCall(Service.Traffic.PICK_UP, SOLUTION_NO_SOLUTION, R.string.makeService)
            )
        }
    }
    

    Then, when you need to display this data in the UI (say a TextView), you can fetch the string from the resource id.

    descriptionTextView.text = getString(phoneCall.description)