Code-formatting: How to align <- inside for-comprehension?

Viewed 1410

I have a for comprehension like this:

 private[helper] def myMethod(name: String, index: Long) = {
   for {
  result1  <- httpUtilities.getLowIndexes(index)
  result2    <- myFacade.queryMaterial(result1)
  result3 <- httpUtilities.someMethod(result2)
  } yield result3
 }

What I wanted is to align special character <- in columns so that above code is transformed to :

private[helper] def myMethod(name: String, index: Long) = {
   for {
      result1  <- httpUtilities.getLowIndexes(index)
      result2  <- myFacade.queryMaterial(result1)
      result3  <- httpUtilities.someMethod(result2)
  } yield result3
 }

I can do the same for match case statements in Settings -> Code Style -> Scala => Wrapping and Braces -> 'match' and 'case' statements -> Align in columns 'case' branches in Intellij but how to do it for <- character inside for-comprehension.

1 Answers

Scalafmt can do exactly this, and it is available as an IDEA plugin, and is packaged many other ways as well.

You want to use the align=more feature, as documented here. The docs show the following examples of alignment:

val x  = 2 // true for assignment
val xx = 22

case object B  extends A // false for `extends`
case object BB extends A

q  -> 22 // true for various infix operators
qq -> 3  // and also comments!

for {
  x  <- List(1) // true for alignment enumerator
  yy <- List(2)
} yield x ** xx

x match { // true for multiple tokens across multiple lines
  case 1  => 1  -> 2  // first
  case 11 => 11 -> 22 // second

  // A blank line separates alignment blocks.
  case `ignoreMe` => 111 -> 222
}

// Align assignments of similar type.
def name   = column[String]("name")
def status = column[Int]("status")
val x      = 1
val xx     = 22

// Align sbt module IDs.
libraryDependencies ++= Seq(
  "org.scala-lang" % "scala-compiler" % scalaVersion.value,
  "com.lihaoyi"    %% "sourcecode"    % "0.1.1"
)
Related