Force compilation error with sealed classes

后端 未结 6 1830
我寻月下人不归
我寻月下人不归 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 13:04

    Our approach avoids to have the function everywhere when auto-completing. With this solution you also have the when return type in compile time so you can continue using functions of the when return type.

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

    You can define this object like so:

    object Do {
        inline infix fun exhaustive(any: T?) = any
    }
    

提交回复
热议问题