From 2fd039b5eb2e9c8827f75a9e9a904f018947be0e Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Fri, 24 Jun 2022 10:43:13 +0200 Subject: [PATCH] [java] redundant cast: don't suggest to remove cast in switch branches without expected type (IDEA-296622) GitOrigin-RevId: 24bebef33ad6d01861a68df1470f2ed2f454c4c8 --- .../src/com/intellij/psi/util/RedundantCastUtil.java | 8 +++++--- .../switchExpressions/RedundantCastInSwitchBranch.java | 8 ++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/java/java-analysis-impl/src/com/intellij/psi/util/RedundantCastUtil.java b/java/java-analysis-impl/src/com/intellij/psi/util/RedundantCastUtil.java index 77bb8a4cd74b..1e23019e2b20 100644 --- a/java/java-analysis-impl/src/com/intellij/psi/util/RedundantCastUtil.java +++ b/java/java-analysis-impl/src/com/intellij/psi/util/RedundantCastUtil.java @@ -1,4 +1,4 @@ -// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. +// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.psi.util; import com.intellij.codeInsight.AnnotationUtil; @@ -736,8 +736,10 @@ public final class RedundantCastUtil { visitSwitchBlockSelector(expression); PsiType expectedTypeByParent = PsiTypesUtil.getExpectedTypeByParent(expression); - for (PsiExpression resultExpression : PsiUtil.getSwitchResultExpressions(expression)) { - addIfNarrowing(resultExpression, expectedTypeByParent); + if (expectedTypeByParent != null) { + for (PsiExpression resultExpression : PsiUtil.getSwitchResultExpressions(expression)) { + addIfNarrowing(resultExpression, expectedTypeByParent); + } } super.visitSwitchExpression(expression); diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/switchExpressions/RedundantCastInSwitchBranch.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/switchExpressions/RedundantCastInSwitchBranch.java index 00661f137128..ee0b834d33d5 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/switchExpressions/RedundantCastInSwitchBranch.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/switchExpressions/RedundantCastInSwitchBranch.java @@ -31,4 +31,12 @@ class RedundantCast { default -> new ArrayList<>(); }; } + + void castForFunctionalExpression(String s) { + (switch (s) { + case "a" -> (Runnable)() -> System.out.println("a"); + case "b" -> (Runnable)() -> System.out.println("b"); + default -> throw new IllegalArgumentException(); + }).run(); + } } \ No newline at end of file