Search code examples
scalafoldleft

folding a list of classes to a single, comma separated string (in Scala)


I have a need to take a list of case classes and convert them to a to a single, comma separated string (with no heading or tailing comma).

case class State(name: String)

def toLine(states: State*): String = {
}

so, toLine(State("one"), State("two"), State("three")) should return one,two,three

here is what I thought of. any better way?

def toLine(states: State*): String = {
  states match {
    case s if s.isEmpty => throw new Exception
    case s => s.tail.foldLeft(s.head.name)(_+","+_) 
  }
}

is there a way to guaranty there will be at least one value in the list?


Solution

  • You can use mkString:

    def toLine(states: State*): String = states.map(_.name).mkString(",")
    

    if you need to ensure at least one element you can do:

    def toLine(state: State, states: State*) = (state +: states).map(_.name).mkString(",")