HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Adding students to rows in a classroom

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
classroomrowsstudentsadding

Problem

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 => r.foreach(println))
}

Solution

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)
}

Code Snippets

var rows: List[Array[Student]] = List[Array[Student]]()
var rows: List[Array[Student]] = List.empty
def total: Int = rows.map(_.length).sum
def addRow(row: Array[Student]) = rows = row :: rows
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)
}

Context

StackExchange Code Review Q#26376, answer score: 4

Revisions (0)

No revisions yet.