Force compilation error with sealed classes

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

    Consider using the recent library by JakeWharton that allows to just use @Exhaustive annotation.

    sealed class RouletteColor {
      object Red : RouletteColor()
      object Black : RouletteColor()
      object Green : RouletteColor()
    }
    
    fun printColor(color: RouletteColor) {
      @Exhaustive
      when (color) {
        RouletteColor.Red -> println("red")
        RouletteColor.Black -> println("black")
      }
    }
    

    Usage:

    buildscript {
      dependencies {
        classpath 'app.cash.exhaustive:exhaustive-gradle:0.1.1'
      }
      repositories {
        mavenCentral()
      }
    }
    
    apply plugin: 'org.jetbrains.kotlin.jvm' // or .android or .multiplatform or .js
    apply plugin: 'app.cash.exhaustive'
    

    Lib: https://github.com/cashapp/exhaustive

提交回复
热议问题