In this article we present several examples of functional programming (FP) in Scala. FP [TH4515 2.1] treats computation as the evaluation of mathematical functions and avoids state and mutable data.
Common operations on collection classes are filter
,
map
and reduce
.
As a first example, the following Java code tests a predicate on a collection of geometric regions containing bouncing balls:
public boolean canStartLineAt(float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { return true; } } return false; }
In Scala, one can express the above predicate test as an anonymous function
and pass it to the appropriate method — exists
in this
case —:
def canStartLineAt(x: Float, y: Float): Boolean = mRegions exists (_.canStartLineAt(x, y))
In this second Java example we return the percentage of the filled surface based on the ratio between the total area of a collection of regions containing bouncing balls and the game board area.
public float getPercentageFilled() { float total = 0f; for (int i = 0; i < mRegions.size(); i++) { BallRegion region = mRegions.get(i); total += region.getArea(); Log.d("Balls", "total now " + total); } return 1f - (total / getArea()); }
In Scala we simply combine two higher-order functions (functions with function arguments) to perform the same operation:
def getPercentageFilled: Float = { val total = mRegions map (_.getArea) reduceLeft (_ + _) 1f - (total / getArea) }