dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
12 stars 0 forks source link

Sealed Classes #94

Open dvas0004 opened 5 years ago

dvas0004 commented 5 years ago

Sealed classes essentially act as enums but at a class level. This allows you to check if a class is of a certain type and call a method or variable depending on that type. Sealed classes allow you to use the when keyword to achieve this:

sealed class Demo
/*
note that the variable names in the constructors of the below data classes are different
so we cannot simply call "demo1.myNumber3" or "demo3.myNumber1". 
The variable depends on which type of data class is used 
(hence necessitating the use of the "when" expression below)

also note that both extend the sealed class "Demo"
*/
data class Demo1(val myNumber1: Int) : Demo()
data class Demo3(val myNumber3: Int) : Demo() 

fun demoTest(demo: Demo){
    when(demo){
        is Demo1 -> println(demo.myNumber1)
        is Demo3 -> println(demo.myNumber3)
    }

}

fun main() {
    val sampleDemo = Demo1(123)
    demoTest(sampleDemo)
}

// results in : 123

It's a bit similar to replace the use of virtual method invocation in java ( see: #73 )

dvas0004 commented 5 years ago

https://pl.kotl.in/A7grCrIJ6