From df3953f03ae64ff99913d1b5b54e410b25c6e81d Mon Sep 17 00:00:00 2001 From: Toshiaki Kameyama Date: Thu, 21 Feb 2019 19:40:02 +0900 Subject: [PATCH] Redundant Unit: fix false positive when return type is nullable Unit #KT-30038 Fixed --- .../idea/inspections/RedundantUnitExpressionInspection.kt | 3 ++- .../redundantUnitExpression/returnAsNullableUnit.kt | 5 +++++ .../idea/inspections/LocalInspectionTestGenerated.java | 5 +++++ 3 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 idea/testData/inspectionsLocal/redundantUnitExpression/returnAsNullableUnit.kt diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantUnitExpressionInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantUnitExpressionInspection.kt index 7c5fe3c5f74..86c6d896ab0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantUnitExpressionInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantUnitExpressionInspection.kt @@ -44,7 +44,8 @@ private fun KtReferenceExpression.isRedundantUnit(): Boolean { if (!isUnitLiteral()) return false val parent = this.parent ?: return false if (parent is KtReturnExpression) { - return parent.expectedReturnType()?.nameIfStandardType != KotlinBuiltIns.FQ_NAMES.any.shortName() + val expectedReturnType = parent.expectedReturnType() ?: return false + return expectedReturnType.nameIfStandardType != KotlinBuiltIns.FQ_NAMES.any.shortName() && !expectedReturnType.isMarkedNullable } if (parent is KtBlockExpression) { // Do not report just 'Unit' in function literals (return@label Unit is OK even in literals) diff --git a/idea/testData/inspectionsLocal/redundantUnitExpression/returnAsNullableUnit.kt b/idea/testData/inspectionsLocal/redundantUnitExpression/returnAsNullableUnit.kt new file mode 100644 index 00000000000..f0877eee062 --- /dev/null +++ b/idea/testData/inspectionsLocal/redundantUnitExpression/returnAsNullableUnit.kt @@ -0,0 +1,5 @@ +// PROBLEM: none + +fun foo(): Unit? { + return Unit +} \ No newline at end of file diff --git a/idea/tests/org/jetbrains/kotlin/idea/inspections/LocalInspectionTestGenerated.java b/idea/tests/org/jetbrains/kotlin/idea/inspections/LocalInspectionTestGenerated.java index e70ba38eca1..65fec55437a 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/inspections/LocalInspectionTestGenerated.java +++ b/idea/tests/org/jetbrains/kotlin/idea/inspections/LocalInspectionTestGenerated.java @@ -5733,6 +5733,11 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest { public void testReturnAsNullableAny() throws Exception { runTest("idea/testData/inspectionsLocal/redundantUnitExpression/returnAsNullableAny.kt"); } + + @TestMetadata("returnAsNullableUnit.kt") + public void testReturnAsNullableUnit() throws Exception { + runTest("idea/testData/inspectionsLocal/redundantUnitExpression/returnAsNullableUnit.kt"); + } } @TestMetadata("idea/testData/inspectionsLocal/redundantVisibilityModifier")