Chapter 6 Functional Objects Or objects without a
Chapter 6: Functional Objects Or… objects without a mutable state
Why use them? • • Simpler and easier to use Less risk Less to worry about with concurrency Nice for things like hash keys However… • No ease of updates is a drag
Construction Class parameters Scala Java class Rational(n: Int, d: Int) public class Rational { private int n; private int d; public Rational(int n, int d) { this. n = n; this. d = d; } }
Preconditions • An advantage of object-oriented design • Validation upon construction
Preconditions class Rational(n: Int, d: Int) { require(d != 0) }
Adding Methods Scala Java override def to. String = s“$n/$d” public String to. String() { return n + "/" + d; }
Adding Methods class Rational(n: Int, d: Int) { def add(that: Rational): Rational = new Rational(n * that. d + that. n * d, d * that. d) } // This code stinks
Class Fields Scala Java class Rational(n: Int, d: Int) { public class Rational { } val numer: Int = n private int numer; val denom: Int = d private int denom; }
Adding Methods class Rational(n: Int, d: Int) { val numer: Int = n val denom: Int = d def add(that: Rational): Rational = new Rational( numer * that. denom + that. numer * denom, denom * that. denom ) } // Less stinkage!
Self References def less. Than(that: Rational) = this. numer * that. denom < that. numer * this. demon def max(that: Rational) = if (less. Than(that)) that else this
Constructor Overloading Scala Java class Rational(n: Int, d: Int) public class Rational { 1) def this(n: Int) = this(n, public Rational(int n) { numer = n; denom = 1; } }
That’s a lot of stuff! class Rational(n: Int, d: Int) { val numer: Int = n val denom: Int = d require(d != 0) def this(n: Int) = this(n, 1) override def to. String = s“$n/$d” def add(that: Rational): Rational = new Rational( numer * that. denom + that. numer * denom, denom * that. denom ) }
Private Stuff class Rational(n: Int, d: Int) { private val g = gcd (n. abs, d. abs) val numer = n / g val denom = d / g private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) }
Operators x add y is fine x + y is cooler!
Operators def + (that: Rational): Rational = new Rational( numer * that. denom + that. numer * denom, denom * that. denom ) // It still works!
Identifiers • Alphanumeric x, y, to. String… Try to avoid underscores • Operator +, -, *, : : : , <? >… Internal identification • Mixed unary_+ • Literal `x` `yield` `pizzeria`
Method Overloading def + (that: Rational): Rational = new Rational( numer * that. denom + that. numer * denom, denom * that. denom ) def + (i: Int): Rational = new Rational( numer + i * denom, denom )
Implicit Conversion implicit def int. To. Rational(x: Int) = new Rational(x)
- Slides: 18