Format lambda chains (#1235)

This changes the formatter to only force line on call chains
with multiple lambdas

With this change, this is kept as a single line:

```
foo.bar.map((it) -> it + 1)
```
This commit is contained in:
Daniel Chao
2025-10-09 10:16:13 -07:00
committed by GitHub
parent 98ab741c54
commit 3a29ea8998
3 changed files with 18 additions and 2 deletions

View File

@@ -803,7 +803,7 @@ internal class Builder(sourceText: String) {
private fun formatBinaryOpExpr(node: Node): FormatNode {
val flat = flattenBinaryOperatorExprs(node)
val callChainSize = flat.count { it.isOperator(".", "?.") }
val hasLambda = callChainSize > 1 && flat.any { hasFunctionLiteral(it, 2) }
val hasMultipleLambdas = callChainSize > 1 && flat.hasMoreThan(1) { hasFunctionLiteral(it, 2) }
val nodes =
formatGeneric(flat) { prev, next ->
if (prev.type == NodeType.OPERATOR) {
@@ -816,7 +816,7 @@ internal class Builder(sourceText: String) {
} else if (next.type == NodeType.OPERATOR) {
when (next.text()) {
".",
"?." -> if (hasLambda) ForceLine else Line
"?." -> if (hasMultipleLambdas) ForceLine else Line
"-" -> Space
else -> SpaceOrLine
}
@@ -1231,6 +1231,18 @@ internal class Builder(sourceText: String) {
}
}
private inline fun <T> Iterable<T>.hasMoreThan(num: Int, predicate: (T) -> Boolean): Boolean {
if (this is Collection && isEmpty()) return false
var count = 0
for (element in this) {
if (predicate(element)) count++
if (count > num) {
return true
}
}
return false
}
companion object {
private val ABSOLUTE_URL_REGEX = Regex("""\w+:.*""")

View File

@@ -3,3 +3,5 @@ res = myList.map((it) -> it.partition).filter((it) -> someList.contains(it))
res2 = myList.map(lambda1).filter(lambda2)
res3 = myList.map((it) -> it.partition)
res4 = myList.foo.map((it) -> it.partition)

View File

@@ -6,3 +6,5 @@ res =
res2 = myList.map(lambda1).filter(lambda2)
res3 = myList.map((it) -> it.partition)
res4 = myList.foo.map((it) -> it.partition)