From 3e14d4f80f99360d45923f0f6170c71e0b0b26b2 Mon Sep 17 00:00:00 2001 From: Johnnei Date: Mon, 16 Jan 2023 21:58:05 +0700 Subject: [PATCH] Allow unit results in if statement if they're captured by a function Fixes #229 --- .../inspections/empty/EmptyIfBlock.scala | 2 ++ .../inspections/empty/EmptyIfBlockTest.scala | 24 ++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/main/scala/com/sksamuel/scapegoat/inspections/empty/EmptyIfBlock.scala b/src/main/scala/com/sksamuel/scapegoat/inspections/empty/EmptyIfBlock.scala index 14907a21..8f259454 100644 --- a/src/main/scala/com/sksamuel/scapegoat/inspections/empty/EmptyIfBlock.scala +++ b/src/main/scala/com/sksamuel/scapegoat/inspections/empty/EmptyIfBlock.scala @@ -23,6 +23,8 @@ class EmptyIfBlock override def inspect(tree: Tree): Unit = { tree match { + // Function directly contains if, an empty block would generate Unit (or Any) output type + case Function(_, If(_, Literal(Constant(())), _)) => // skip tree case If(_, Literal(Constant(())), _) => context.warn(tree.pos, self, tree.toString.take(500)) case _ => continue(tree) diff --git a/src/test/scala/com/sksamuel/scapegoat/inspections/empty/EmptyIfBlockTest.scala b/src/test/scala/com/sksamuel/scapegoat/inspections/empty/EmptyIfBlockTest.scala index c02b4eda..e3757b71 100644 --- a/src/test/scala/com/sksamuel/scapegoat/inspections/empty/EmptyIfBlockTest.scala +++ b/src/test/scala/com/sksamuel/scapegoat/inspections/empty/EmptyIfBlockTest.scala @@ -10,7 +10,8 @@ class EmptyIfBlockTest extends InspectionTest { "empty if block" - { "should report warning" in { - val code = """object Test { + val code = + """object Test { if (true) { } @@ -28,5 +29,26 @@ class EmptyIfBlockTest extends InspectionTest { compileCodeSnippet(code) compiler.scapegoat.feedback.warnings.size shouldBe 2 } + + "should not report warning" - { + "the if-block is the return value" in { + val code = + """ + |import scala.concurrent.Future + |import scala.concurrent.ExecutionContext.Implicits.global + |object Test { + | Future("test").map(value => { + | if (value.contains("foo")) { + | () + | } else { + | throw new IllegalStateException("Bar!") + | } + | }) + |}""".stripMargin + + compileCodeSnippet(code) + compiler.scapegoat.feedback.warnings.size shouldBe 0 + } + } } }