Do we have better way to simplify this code?

Solution 1:

You could do this:

viewModel.apply {
        val customized = data.section_type == "customized"
        sectionTypeId = if(customized) data.id ?: 0 else 0
        specialSectionId = if(customized) data.id ?: 0 else 0
        specialSectionName = if(customized) data.name ?: "" else ""
    }

Solution 2:

Since there is no ternary operator in kotlin, you can use if expressions and assign repeated code to values like this:

viewModel.apply {
    val customized = data.section_type == "customized"
    val iD = if(customized) data.id ?: 0 else 0
    sectionTypeId = iD
    specialSectionId = iD
    specialSectionName = if(customized) data.name ?: "" else ""
}