Adding students to rows in a classroom I'm learning Scala and functional programming. Can I make it more functional?

class Student(val firstname: String, val lastname: String) {
  override def toString: String = firstname + " " + lastname
}
class ClassRoom {
  var rows: List[Array[Student]] = List[Array[Student]]()
  var total: Int = _
  def addRow(row: Array[Student]) = {
    rows = row :: rows
    total += row.length
  }
  def print = rows.foreach(r =&gt; r.foreach(println))
}
A couple of small things to start.

var rows: List[Array[Student]] = List[Array[Student]]()


This line can be simplified slightly by doing this instead:

var rows: List[Array[Student]] = List.empty


Unless you are caching the total for performance reasons, you could calculate it as needed with something like this:

def total: Int = rows.map(_.length).sum


That would simplify addRow() to this:

def addRow(row: Array[Student]) = rows = row :: rows




One of the tenets of functional programming is the use of immutable data. ClassRoom is not very functional from this perspective: both rows and total are mutable. If you wanted to take a pure functional approach, all members would be val and functions like addRow() would return a new ClassRoom instead of modifying itself. For example:

class ClassRoom(val rows: List[Array[Student]]) {
  def total: Int = rows.map(_.length).sum
  def addRow(row: Array[Student]) = new ClassRoom(row :: rows)
  def print = rows.foreach(_ foreach println)
}