Force compilation error with sealed classes

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

    A discussion triggered me to look for a more general solution and found one, for Gradle builds. It doesn't require changing the source code! The drawback is that compilation may become noisy.

    build.gradle.kts

    tasks.withType().configureEach {
        val taskOutput = StringBuilder()
        logging.level = LogLevel.INFO
        logging.addStandardOutputListener { taskOutput.append(it) }
        doLast {
            fun CharSequence.hasInfoWithError(): Boolean =
                "'when' expression on sealed classes is recommended to be exhaustive" in this
            if (taskOutput.hasInfoWithError()) {
                throw Exception("kotlinc infos considered as errors found, see compiler output for details.")
            }
        }
    }
    

    build.gradle

    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
        def taskOutput = new StringBuilder()
        logging.level = LogLevel.INFO
        logging.addStandardOutputListener(new StandardOutputListener() {
            void onOutput(CharSequence text) { taskOutput.append(text) }
        })
        doLast {
            def hasInfoWithError = { CharSequence output ->
                output.contains("'when' expression on sealed classes is recommended to be exhaustive")
            }
            if (hasInfoWithError(taskOutput)) {
                throw new Exception("kotlinc infos considered as errors found, see compiler output for details.")
            }
        }
    }
    
    

    Notes:

    • Change implementation of hasInfoWithError to generalize to other i:s.
    • Put this code in subprojects { } or allprojects { } to apply project-wide.

    References:

    • Issue tracking making missing sealed case as warning:
      (which together with kotlinOptions.allWarningsAsErrors would solve the issue)
      https://youtrack.jetbrains.com/issue/KT-37651
    • Discussion triggering this solution:
      https://youtrack.jetbrains.com/issue/KT-12380#focus=streamItem-27-4017839.0-0
    • Repo with working example:
      https://github.com/TWiStErRob/repros/tree/master/kotlin/fail-on-sealed-when-info

提交回复
热议问题