Created
June 9, 2015 06:43
-
-
Save asarkar/ef57fd7d0e55e8745371 to your computer and use it in GitHub Desktop.
Scala Closure Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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