Force compilation error with sealed classes

后端 未结 6 1970
我寻月下人不归
我寻月下人不归 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条回答
  •  -上瘾入骨i
    2020-12-28 12:43

    In inspiration by Voddan's answer, you can build a property called safe you can use:

    val Any?.safe get() = Unit
    

    To use:

    when (sealedClass) {
        is SealedClass.First -> doSomething()
        is SealedClass.Second -> doSomethingElse()
    }.safe
    

    I think it provides a clearer message than just appending .let{} or assigning the result to a value.


    There is an open issue on the Kotlin tracker which considers to support 'sealed whens'.

提交回复
热议问题