Skip to content

Instantly share code, notes, and snippets.

@asarkar
Created June 9, 2015 06:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asarkar/ef57fd7d0e55e8745371 to your computer and use it in GitHub Desktop.
Save asarkar/ef57fd7d0e55e8745371 to your computer and use it in GitHub Desktop.
Scala Closure Demo
public class Fraction {
private final int num;
private final int denom;
public Fraction(int num, int denom) {
this.num = num;
this.denom = denom;
}
public int getNum() {
return num;
}
public int getDenom() {
return denom;
}
public Fraction add(Fraction other) {
// Ignore cases where denom is 0 or other.denom is 0 or other is null. Also assume the denom are the same for both fractions
return new Fraction(num + other.num, denom)
}
public Fraction subtract(Fraction other) {
// Ignore cases where denom is 0 or other.denom is 0 or other is null. Also assume the denom are the same for both fractions
return new Fraction(num - other.num, denom)
}
}
class Fraction(val num: Int, val denom: Int) {
def +(that: Fraction) = {
op(that) { _ + _ }
}
def -(that: Fraction) = {
op(that) { _ - _ }
}
private def op(that: Fraction)(f: (Int, Int) => Int) = {
// Common error handling goes here. Also goes logic to find LCD if denom are not the same
new Fraction(f.apply(num, that.num), denom)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment