Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OptionalWhenBraces: fix false positive with lambda which has no arrow #2568

Merged
merged 1 commit into from Apr 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -9,6 +9,7 @@ import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.hasCommentInside
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtWhenExpression

/**
Expand Down Expand Up @@ -40,15 +41,16 @@ class OptionalWhenBraces(config: Config = Config.empty) : Rule(config) {
override fun visitWhenExpression(expression: KtWhenExpression) {
for (entry in expression.entries) {
val blockExpression = entry.expression as? KtBlockExpression
if (hasOneStatement(blockExpression) && hasOptionalBrace(blockExpression)) {
if (blockExpression?.hasUnnecessaryBraces() == true) {
report(CodeSmell(issue, Entity.from(entry), issue.description))
}
}
}

private fun hasOneStatement(blockExpression: KtBlockExpression?) =
blockExpression?.statements?.size == 1 && !blockExpression.hasCommentInside()

private fun hasOptionalBrace(blockExpression: KtBlockExpression?) =
blockExpression != null && blockExpression.lBrace != null && blockExpression.rBrace != null
private fun KtBlockExpression.hasUnnecessaryBraces(): Boolean {
val singleStatement = statements.singleOrNull()?.takeIf {
!(it is KtLambdaExpression && it.functionLiteral.arrow == null)
}
return singleStatement != null && !hasCommentInside() && lBrace != null && rBrace != null
}
}
Expand Up @@ -38,5 +38,31 @@ class OptionalWhenBracesSpec : Spek({
}"""
assertThat(subject.compileAndLint(code)).hasSize(1)
}

context("the statement is a lambda expression") {
it("does not report if the lambda has no arrow") {
val code = """
fun test(b: Boolean): (Int) -> Int {
return when (b) {
true -> { { it + 100 } }
false -> { { it + 200 } }
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}

it("reports if the lambda has an arrow") {
val code = """
fun test(b: Boolean): (Int) -> Int {
return when (b) {
true -> { { i -> i + 100 } }
false -> { { i -> i + 200 } }
}
}
"""
assertThat(subject.compileAndLint(code)).hasSize(2)
}
}
}
})