Force compilation error with sealed classes

后端 未结 6 2011
我寻月下人不归
我寻月下人不归 2020-12-28 12:12

With sealed classes you can use exhaustive when expressions and omit the else clause when the expression returns a result:

sealed c         


        
6条回答
  •  清酒与你
    2020-12-28 12:55

    The way to enforce exhaustive when is to make it an expression by using its value:

    sealed class SealedClass {
        class First : SealedClass()
        class Second : SealedClass()
        class Third : SealedClass()
    }
    
    fun test(sealedClass: SealedClass) {
        val x = when (sealedClass) {
            is SealedClass.First -> doSomething()
            is SealedClass.Second -> doSomethingElse()
        }  // ERROR here
    
        // or
    
        when (sealedClass) {
            is SealedClass.First -> doSomething()
            is SealedClass.Second -> doSomethingElse()
        }.let {}  // ERROR here
    }
    

提交回复
热议问题