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

Report Unit returned by method implementations in interfaces #3108

Merged
merged 2 commits into from
Sep 27, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,11 @@ import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.isOverride
import org.jetbrains.kotlin.cfg.WhenChecker
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
Expand Down Expand Up @@ -56,9 +54,7 @@ class OptionalUnit(config: Config = Config.empty) : Rule(config) {
Debt.FIVE_MINS)

override fun visitNamedFunction(function: KtNamedFunction) {
if (function.funKeyword == null) return
if (isInInterface(function)) return
if (function.hasDeclaredReturnType() && function.colon != null) {
if (function.hasDeclaredReturnType()) {
checkFunctionWithExplicitReturnType(function)
} else if (!function.isOverride()) {
checkFunctionWithInferredReturnType(function)
Expand Down Expand Up @@ -117,9 +113,6 @@ class OptionalUnit(config: Config = Config.empty) : Rule(config) {
}
}

private fun isInInterface(function: KtNamedFunction) =
function.getStrictParentOfType<KtClass>()?.isInterface() ?: false

private fun createMessage(function: KtNamedFunction) = "The function ${function.name} " +
"defines a return type of Unit. This is unnecessary and can safely be removed."

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,14 +116,14 @@ class OptionalUnitSpec : Spek({
}

context("a default interface implementation") {
it("should not report Unit as part of default interface implementations") {
it("should report Unit as part of default interface implementations") {
val code = """
interface Foo {
fun method(i: Int) = Unit
}
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
assertThat(findings).hasSize(1)
}
}

Expand Down