ktfmt icon indicating copy to clipboard operation
ktfmt copied to clipboard

Formatting of lambda followed by `.asSequence()` is a bit strange

Open jbduncan opened this issue 2 years ago • 3 comments

I recently wrote some code like in the dropdown below, which uses ShortestPath from github.com/google/mug, and which I was hoping ktfmt would leave as-is:

Original code, expected to be left as-is
package foo.bar

import com.google.mu.util.graph.ShortestPath
import java.util.stream.Stream
import kotlin.streams.asSequence

fun main(args: Array<String>) {
  val start = 1.0
  val end = 3.0
  val path =
    ShortestPath.unweightedShortestPathsFrom(start) {
        Stream.of(2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
      }
      .asSequence()
      .first { path -> path.to() == end }
  println(path)
}

However, when running ktfmt 0.30 on this code with Spotless, it produces this:

Actual code
package foo.bar

import com.google.mu.util.graph.ShortestPath
import java.util.stream.Stream
import kotlin.streams.asSequence

fun main(args: Array<String>) {
  val start = 1.0
  val end = 3.0
  val path =
    ShortestPath.unweightedShortestPathsFrom(start) {
      Stream.of(2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) // <- unintended by 2 spaces
    } // <- unindented by two spaces
      .asSequence()
      .first { path -> path.to() == end }
  println(path)
}

ktfmt 0.30 leaves the code's indentation alone if I change it to use .filter { ... } instead of .asSequence():

Unaffected code
package foo.bar

import com.google.mu.util.graph.ShortestPath
import java.util.stream.Stream

fun main(args: Array<String>) {
  val start = 1.0
  val end = 3.0
  val path =
    ShortestPath.unweightedShortestPathsFrom(start) {
        Stream.of(2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
      }
      .filter { path -> path.to() == end }
      .findAny()
      .orElseThrow()
  println(path)
}

It's not clear to me if this is happening because .asSequence() is a Kotlin extension function, which might be tripping something up in ktfmt, or for some other reason.

jbduncan avatar Jan 31 '22 00:01 jbduncan