diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionLiteralRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionLiteralRule.kt index 25314e50c1..7c6e0bff37 100644 --- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionLiteralRule.kt +++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionLiteralRule.kt @@ -49,6 +49,7 @@ import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe import com.pinterest.ktlint.ruleset.standard.StandardRule import io.github.oshai.kotlinlogging.KotlinLogging import org.jetbrains.kotlin.com.intellij.lang.ASTNode +import org.jetbrains.kotlin.psi.psiUtil.siblings private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger() @@ -343,8 +344,8 @@ public class FunctionLiteralRule : ) { require(parameterList.elementType == VALUE_PARAMETER_LIST) parameterList - .prevSibling { it.isWhiteSpace() } - ?.takeIf { it.isWhiteSpaceWithNewline() } + .takeUnless { it.isPrecededByComment() } + ?.prevSibling { it.isWhiteSpaceWithNewline() } ?.let { whitespaceBeforeParameterList -> emit(parameterList.startOffset, "No newline expected before parameter", true) .ifAutocorrectAllowed { @@ -362,6 +363,8 @@ public class FunctionLiteralRule : } } + private fun ASTNode.isPrecededByComment() = siblings(forward = false).any { it.isPartOfComment() } + private fun visitArrow( arrow: ASTNode, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> AutocorrectDecision, diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionLiteralRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionLiteralRuleTest.kt index 0ebefd4ac6..5dc842921a 100644 --- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionLiteralRuleTest.kt +++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/FunctionLiteralRuleTest.kt @@ -597,4 +597,30 @@ class FunctionLiteralRuleTest { LintViolation(4, 7, "Arrow is redundant when parameter list is empty"), ).isFormattedAs(formattedCode) } + + @Test + fun `Issue 2850 - Given function literal with a comment before the parameter list which contains a redundant parameter then do remove the redundant parameter but keep the comment`() { + val code = + """ + val foo1 = + { + // some comment + foo: String -> "foo = " + foo + } + val foo2 = + { // some comment + foo: String -> "foo = " + foo + } + val foo3 = + { + /* some comment */ + foo: String -> "foo = " + foo + } + val foo4 = + { /* some comment */ + foo: String -> "foo = " + foo + } + """.trimIndent() + functionLiteralRuleAssertThat(code).hasNoLintViolations() + } }