Skip to content

Instantly share code, notes, and snippets.

@drawers
Created March 30, 2023 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drawers/9bdc1b471a6a96ffe346904b1ce947bf to your computer and use it in GitHub Desktop.
Save drawers/9bdc1b471a6a96ffe346904b1ce947bf to your computer and use it in GitHub Desktop.
import io.gitlab.arturbosch.detekt.api.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
class DoubleNegativeTakeUnless(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
"DoubleNegativeTakeUnless",
Severity.Style,
"Using double negatives with `takeUnless` can make the code harder to read.",
Debt.FIVE_MINS
)
override fun visitCallExpression(expression: KtCallExpression) {
val calleeExpression = expression.calleeExpression?.text ?: return
if (calleeExpression == "takeUnless") {
val lambdaExpression = expression.lambdaArguments.firstOrNull() ?: return
val negations = lambdaExpression.collectDescendantsOfType<KtPrefixExpression> {
it.baseExpression?.let { baseExpr ->
baseExpr is KtSimpleNameExpression && it.operationReference.text == "!"
} ?: false
}
if (negations.isNotEmpty()) {
report(
CodeSmell(
issue,
Entity.from(expression),
"Double negative detected with `takeUnless`. " +
"Consider using `takeIf` and simplifying the condition."
)
)
}
}
super.visitCallExpression(expression)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment