Kotlin / Kotlin/ktfmt

Strange formatting for lambda with chained function call

Open
#589 14 comments 3 reactions 0 assignees Claimed by @ptitjes View on GitHub
Dominant language
Kotlin
Stars
1.3k
Forks
116
Avg merge
4d 10h
Merged PRs (30d)
15

Description

The formatter considers the following as properly formatted:
(kotlinlang-style)
```kotlin
fun quux() =
runnnnn {
foo()
bar()
}
.baz()
```
(Java-like)
```kotlin
fun quux() =
runnnnn {
foo()
bar()
}
.baz()
```
It seems to be adding a continuation indentation to the ending brace and the content of the lambda
Is this intentional behaviour? It looks really strange to me, personally.
It happens without the single-expression body as well:
```kotlin
fun quux() {
runnnnn {
foo()
bar()
}
.baz()
}
```
What I'd prefer instead is this:
```kotlin
fun quux() {
runnnnn {
foo()
bar()
}.baz()
}
```
i.e. the ending brace should always have the same indentation as the starting brace, and thus the lambda should always have block indentation, and nothing more. For the `.baz()` call, I'm fine with whatever. It can be on a separate line, or the same line, or floating, or anything like that. I just dislike the idea that lambdas float in such a strange way.
For what it's worth, `try-catch` handles this elegantly IMO:
```kotlin
fun quux() {
try {
foo()
bar()
} catch (_: Throwable) {
foo()
bar()
}
}
```
```kotlin
fun quux() {
try {
foo()
bar()
} catch (_: Throwable) {}
}
```
and similarly with infix calls and operators:
```kotlin
fun quux() {
runnnnnn {
foo()
bar()
} + baz()
}
```
```kotlin
fun quux() {
runnnnnn {
foo()
bar()
} inny baz()
}
```
so I'd call this "precedent"

Contributor guide

Open the contributing guide

Research direction

Reproduce the issue's lambda-plus-chained-call examples with ktfmt, including the single-expression and block-body forms. Compare the current output with the preferred formatting in the report and check the analogous try-catch, infix-call, and operator examples. Done means the lambda body and closing brace no longer receive the unwanted continuation indentation.

Written by the indexing model from the issue text.

Assessment

Tech stack
kotlin
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.