Core Java

Java 8 functional interfaces – random musings implementing a Scala type

In one of the assignments of the Functional programming with Scala course a type called Terrain is introduced – Terrain represents a region parts of which are accessible and parts which are not. So in a very clever way Terrain is defined the following way in the assignment:
 
 
 
 
 
 
 

case class Pos(x:Int, y: Int)

type Terrain = Pos => Boolean

Essentially Terrain is a function which takes a position and for that position returns a boolean based on whether the position is accessible or not!

Given this definition of Terrain, a way to define an “infinite” terrain where every position is accessible is done this way:

val infiniteTerrain = (pos: Pos) => true

or another terrain, where certain coordinates are accessible can be defined this way:

def terrainFunction(vector: Vector[Vector[Char]]) : Terrain = {
 (pos: Pos) => {
  if (pos.x > vector.size - 1 || pos.y > vector(0).size - 1 || pos.x < 0 || pos.y < 0) {
   false
  } else {
   val ch = vector(pos.x)(pos.y)
   ch == 'o';
  }
 }
}  

val terrain1 = terrainFunction(Vector(
     Vector('-','-','-'),
     Vector('-','o','-'),
     Vector('-','o','-'),
     Vector('-','o','-'),
     Vector('-','-','-')
     )
    )

All extremely clever.

Now, given that Java 8 release is imminent, an equally(almost :-) ) clever code can be attempted using Java 8 constructs:

whereas the Terrain could be defined as a function signature in Scala, it has to be defined as a functional interface with Java 8:

interface Terrain {
 public boolean isAccessible(Pos pos);
}

Given this interface, an infinite terrain looks like this using Lambdas in Java 8:

Terrain infiniteTerrain = (pos) -> true;

The terrainFunction equivalent in Java 8 can be defined along these lines:

public Terrain terrainFunction(char[][] arr) {
 return (pos) -> {
  if (pos.x > arr.length - 1 || pos.y > arr[0].length - 1 || pos.x < 0 || pos.y < 0) {
   return false;
  } else {
   char ch = arr[pos.x][pos.y];
   return ch == 'o';
  }
 };
}

char[][] arr = {
 {'-','-','-'},
 {'-','o','-'},
 {'-','o','-'},
 {'-','o','-'},
 {'-','-','-'}
};
Terrain terrain = terrainFunction(arr); 

assertTrue(terrain.isAccessible(new Pos(1, 1)));

Close enough!

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button