With sealed classes you can use exhaustive when
expressions and omit the else
clause when the expression returns a result:
sealed c
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:
hasInfoWithError
to generalize to other i:
s.subprojects { }
or allprojects { }
to apply project-wide.References:
kotlinOptions.allWarningsAsErrors
would solve the issue)