PsiExpression (PsiExpression original, Project project, PsiType type) { // remove nested casts PsiElement expression = PsiUtil.deparenthesizeExpression(original); if (expression == null) return null; if (type.equals(PsiTypes.nullType())) return null; PsiElementFactory factory = JavaPsiFacade.getElementFactory(original.getProject()); String newLiteral = tryConvertNumericLiteral(expression, type); if (newLiteral != null) { return factory.createExpressionFromText(newLiteral, null); } if (type instanceof PsiEllipsisType) type = ((PsiEllipsisType)type).toArrayType(); String text = "(" + type.getCanonicalText(false) + ")value"; PsiTypeCastExpression typeCast = (PsiTypeCastExpression)factory.createExpressionFromText(text, original); typeCast = (PsiTypeCastExpression)JavaCodeStyleManager.getInstance(project).shortenClassReferences(typeCast); typeCast = (PsiTypeCastExpression)CodeStyleManager.getInstance(project).reformat(typeCast); if (expression instanceof PsiConditionalExpression) { // we'd better cast one branch of ternary expression if we can PsiConditionalExpression conditional = (PsiConditionalExpression)expression.copy(); PsiExpression thenE = conditional.getThenExpression(); PsiExpression elseE = conditional.getElseExpression(); PsiType thenType = thenE == null ? null : thenE.getType(); PsiType elseType = elseE == null ? null : elseE.getType(); if (elseType != null && thenType != null) { boolean replaceThen = !TypeConversionUtil.isAssignable(type, thenType); boolean replaceElse = !TypeConversionUtil.isAssignable(type, elseType); if (replaceThen != replaceElse) { if (replaceThen) { Objects.requireNonNull(typeCast.getOperand()).replace(thenE); thenE.replace(typeCast); } else { Objects.requireNonNull(typeCast.getOperand()).replace(elseE); elseE.replace(typeCast); } return conditional; } } } Objects.requireNonNull(typeCast.getOperand()).replace(expression); return typeCast; }