patternMinor
Adding students to rows in a classroom
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.
This line can be simplified slightly by doing this instead:
Unless you are caching the
That would simplify
One of the tenets of functional programming is the use of immutable data.
var rows: List[Array[Student]] = List[Array[Student]]()This line can be simplified slightly by doing this instead:
var rows: List[Array[Student]] = List.emptyUnless you are caching the
total for performance reasons, you could calculate it as needed with something like this:def total: Int = rows.map(_.length).sumThat would simplify
addRow() to this:def addRow(row: Array[Student]) = rows = row :: rowsOne 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.emptydef total: Int = rows.map(_.length).sumdef addRow(row: Array[Student]) = rows = row :: rowsclass 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.