title: Scala split list into multiple lists
body: <p>I need to split a List into multiple list based on sum of size of an element. So this is what I wrote in to achieve this.
  I am sure there will be a better way to write same in Scala. Any help is appreciated.</p>
  
  <p>here is my code...</p>
  
  <pre><code>case class cs(name: String, size: Int)
  val cl: List[cs] = List(cs("abc1", 3), cs("abc2", 2), cs("abc3", 1), cs("abc4", 2), cs("abc5", 2), cs("abc6", 1), cs("abc7", 5))
  
  def splitBy(l: List[cs], chunkSize: Int = 5): List[List[cs]] = {
  
    var s = 0
    var tcl: List[cs] = List[cs]()
    var mcl: List[List[cs]] = List[List[cs]]()
  
    l.foreach{ e =&gt; {
      s = s + e.size
      if (s &gt; chunkSize) {
        mcl = tcl +: mcl
        s = e.size
        tcl = Nil
      }
      tcl = e +: tcl
      println("TSize: " + tcl.size + " Elem: " + e + "Sum: " + s)
    }
    }
  
    mcl
  
  }
  
  println(splitBy(cl,5))
  </code></pre>