Kotlin密闭类的使用场景

2,317 阅读1分钟

Kotlin密闭类对于Java开发者来说完全是一个全新的概念。它是枚举的升级版,相对了枚举它多了一个传参的功能。这点跟swift的枚举很像,我猜是参考swift的枚举功能来设计的。

swift的枚举

相对于Java的枚举来说,swift的枚举实例支持传递参数


    public enum Message {
        case showChart
        case showData(message: String, visible: Bool)
    }
    
   public func receive(_ message: Message) {
        switch message {
        case let .showData(msg: String, visible: Bool):
            print(msg) 
        default:
            break
        }
    }

密闭类sealed class的用法

举一个很简单很常见的例子,Presenter层需要通知View层展示或者隐藏LoadingView,正常我们会这样写

interface ISplashBaseView : IView {
    fun showLoading()
    fun hideLoading()
}

改写枚举的话,会这样写。这种方式View成只对外暴露一个接口方法,相对来说会比较清晰易于管理

enum class Event {
    SHOW_LOADING, HIDE_LOADING
}

interface ISplashBaseView : IView {
    fun sendEvent(event: Event)
}

但是,新增一个需求,通知View层去展示一段内容,用枚举就没办法实现。这个时候就需要用到密闭类。下面看一下密闭类的用法,密闭类一般结合Kotlinwhen一起使用

sealed class UIEvent {
    object ShowLoading: UIEvent()
    object HideLoading: UIEvent()
    class ShowData(val message: String): UIEvent()
}


interface ISplashBaseView : IView {
    fun sendEvent(event: UIEvent)
}

class MainActivity() : BaseActivity(), ISplashBaseView {
    override fun sendEvent(event: UIEvent) {
        when (event) {
            is UIEvent.ShowLoading -> showLoading()
            is UIEvent.HideLoading -> hideLoading()
            is UIEvent.ShowData -> showData(event.message)
        }
    }

    private fun showLoading() {

    }

    private fun hideLoading() {

    }

    private fun showData(message: String) {

    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_main
    }
}

一些思考