Skip to content

Suggesting all possible options of state using sealed class

Devrath edited this page Aug 9, 2022 · 2 revisions

Suggesting all possible options

  • If we use when option, the compiler will recommend all the options(subclasses) of the sealed class state.
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val catData = getCats()

        when(catData){
            is Camel -> { /* Some logic */ }
            is Animal.Cat -> { /* Some logic */ }
            is Animal.Dog -> { /* Some logic */ }
            is Monkey -> { /* Some logic */ }
        }

    }

    fun getCats() : Animal {  return Animal.Cat }

}

Animal.kt: -> Class containing all states

package com.demo.subclasses

sealed class Animal {
    object Cat : Animal() // We can define a Object classes like this
    data class Dog(val name: String) : Animal() // We can define data classes like this
}
object Camel : Animal()
object Monkey : Animal()

Representation of all kinds of events

  • We can have one file, it can be a class
  • Have a sealed class and the subclasses in that file itself
  • Then use it to define the events

Here is an example of it

import java.math.BigDecimal

sealed class Payment
data class CashPayment(val amount: BigDecimal, val pointId: Int): Payment()
data class CardPayment(val amount: BigDecimal, val orderId: Int): Payment()
data class BankTransfer(val amount: BigDecimal, val orderId: Int): Payment()

fun process(payment: Payment) {
    when (payment) {
        is CashPayment -> {
            showPaymentInfo(payment.amount, payment.pointId)
        }
        is CardPayment -> {
            moveToCardPaiment(payment.amount, payment.orderId)
        }
        is BankTransfer -> {
            moveToCardPaiment(payment.amount, payment.orderId)
        }
    }
}
Clone this wiki locally