본문 바로가기
Projects/ATeen

[Android/Kotlin] open 메서드를 활용한 다형성 구현

by quessr 2024. 8. 26.

Kotlin에서 클래스나 메서드를 정의할 때, open 키워드를 사용하면 상속받은 클래스에서 해당 메서드를 오버라이드할 수 있습니다. 이번 포스팅에서는 open fun onBind(profileDetailModel: ProfileDetailModel) {} 메서드를 예로 들어, 이 메서드가 어떤 역할을 하고, 어떻게 활용될 수 있는지에 대해 설명하겠습니다.

 

open 키워드와 메서드 오버라이드

Kotlin에서는 기본적으로 모든 클래스와 메서드가 final로 선언됩니다. 이는 서브클래스에서 해당 클래스나 메서드를 상속하거나 오버라이드할 수 없음을 의미합니다. 그러나, 클래스나 메서드를 open으로 선언하면, 이를 서브클래스에서 확장하거나 오버라이드할 수 있게 됩니다.

예를 들어, 다음과 같은 ProfileDetailViewHolder 클래스를 정의할 수 있습니다.

 

sealed class ProfileDetailViewHolder(binding: ViewBinding) : RecyclerView.ViewHolder(binding.root) {

    open fun onBind(profileDetailModel: ProfileDetailModel) {}
    
    class Info(private val binding: ItemProfileDetailInfoBinding) :
        ProfileDetailViewHolder(binding) {
        override fun onBind(profileDetailModel: ProfileDetailModel) {
            val profileInfo = profileDetailModel as? ProfileDetailModel.ProfileInfo
            profileInfo?.let {
                binding.tvName.text = it.name
                binding.tvAge.text = "${it.age}세"
                binding.tvSchool.text = "${it.school}, "
            }
        }
    }

    // ... 
}

 

이 코드에서 onBind 메서드는 open 키워드를 사용하여 선언되었기 때문에, 서브클래스에서 이 메서드를 오버라이드하여 각기 다른 로직을 구현할 수 있습니다.

 

onBind(profileDetailModel: ProfileDetailModel) 메서드의 역할

이 메서드는 ProfileDetailViewHolder 클래스와 그 서브클래스들에서 공통된 인터페이스로 작동합니다. 이를 통해 RecyclerView의 어댑터에서 각 뷰 홀더에 데이터를 바인딩할 때 일관된 접근 방식을 사용할 수 있습니다.

일반적으로, RecyclerView.Adapter 클래스에서는 onBindViewHolder 메서드가 호출됩니다. 이 메서드는 각각의 뷰 홀더에 데이터를 전달하는 역할을 합니다. onBind 메서드는 이 과정에서 호출되어, 서브클래스별로 데이터를 어떻게 바인딩할지를 정의하게 됩니다.

 

서브클래스에서의 오버라이드

서브클래스에서는 onBind 메서드를 오버라이드하여, 각기 다른 타입의 ProfileDetailModel에 대한 바인딩 로직을 구현할 수 있습니다.

예를 들어, Info 서브클래스에서는 ProfileDetailModel.ProfileInfo 타입에 맞게 데이터를 바인딩할 수 있습니다.

class Info(private val binding: ItemProfileDetailInfoBinding) :
    ProfileDetailViewHolder(binding) {
    override fun onBind(profileDetailModel: ProfileDetailModel) {
        val profileInfo = profileDetailModel as? ProfileDetailModel.ProfileInfo
        profileInfo?.let {
            binding.tvName.text = it.name
            binding.tvAge.text = "${it.age}세"
            binding.tvSchool.text = "${it.school}, "
        }
    }
}

 

이렇게 오버라이드된 onBind 메서드는 부모 클래스의 onBind 메서드와 동일한 이름을 가지며, 서브클래스에서 각기 다른 데이터 타입에 대한 바인딩 로직을 처리할 수 있습니다.

다형성의 활용

onBind 메서드를 활용하면, RecyclerView 어댑터에서 다형성을 쉽게 구현할 수 있습니다. 예를 들어, 어댑터에서 onBindViewHolder 메서드를 구현할 때, 부모 클래스의 onBind 메서드를 호출하여 서브클래스별로 데이터를 바인딩할 수 있습니다.

override fun onBindViewHolder(holder: ProfileDetailViewHolder, position: Int) {
    val profileDetailModel = getItem(position)
    holder.onBind(profileDetailModel)
}

 

이렇게 하면, 각 뷰 홀더가 자신의 타입에 맞는 ProfileDetailModel을 바인딩하도록 할 수 있습니다. 이는 코드의 일관성을 유지하면서도 다양한 타입의 데이터를 처리할 수 있게 해줍니다.

결론

Kotlin에서 open 메서드를 사용하는 것은 다형성을 구현하는 데 매우 유용합니다. onBind 메서드는 각 서브클래스에서 다양한 데이터 타입을 처리하기 위해 오버라이드될 수 있으며, 이를 통해 코드의 유연성과 재사용성을 높일 수 있습니다. 이러한 접근 방식은 특히 RecyclerView와 같은 상황에서 매우 효과적입니다.