How do I define my own data structures in Scala? Or does Scala does support some encapsulation mechanism?
Class similar to Java are supported in Scala. I wonder if Scala support Class then is Scala object oriented? Need to give a serious thought on this question. Any ways let me not create confusion here and first discuss the class constructs supported in Scala. Below example discuss encapsulation of rational number type and supporting various arithmetic associated.
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
package learn.scala | |
/** | |
* Datastructures in Scala | |
* The example below shows abstracting Rational numbers and implementing | |
* rational number arithmetics. | |
* | |
* Similar to java scala does provide toString for printing the datastructure representation. | |
* In the example below we override toString method. Also, we make use of this construct which | |
* is also available in Scala. | |
* Introduction to the access modifiers here GCD for example | |
* pre checks using require function | |
*/ | |
class Rational(x: Int, y: Int) { | |
// represents a check on denominator | |
require(y != 0, "Denominator must be a non zero") | |
// private GCD definition abstracted from client | |
private def gcd(x: Int, y: Int): Int = if (y==0) x else gcd(y, x % y) | |
// another constructor other than default expressed in the definition to support integers | |
// all integers are rational with denominator as 1 | |
def this(x: Int) = this(x, 1) | |
def numerator = x | |
def denominator = y | |
def sum ( rational: Rational): Rational = { | |
val newNumer = (this.numerator * rational.denominator) + (this.denominator * rational.numerator) | |
val newDenom = this.denominator * rational.denominator | |
val result = new Rational(newNumer, newDenom) | |
result | |
} | |
def less(that: Rational): Boolean = this.numerator * that.denominator < that.numerator * this.denominator | |
override def toString = (this.numerator / gcd(this.numerator, this.denominator)) + "/" + (this.denominator / gcd(this.numerator, this.denominator)) | |
} | |
object DataStructureExample { | |
val rational = new Rational (1, 2) //> rational : learn.scala.Rational = 1/2 | |
rational.numerator //> res0: Int = 1 | |
rational.denominator //> res1: Int = 2 | |
// ---------------- adding two rational number ------------------ | |
val rational1 = new Rational(5,6) //> rational1 : learn.scala.Rational = 5/6 | |
val rational2 = rational.sum(rational1) //> rational2 : learn.scala.Rational = 4/3 | |
rational2.numerator //> res2: Int = 16 | |
rational2.denominator //> res3: Int = 12 | |
rational1.less(rational2) //> res4: Boolean = true | |
println(rational2) //> 4/3 | |
} |
No comments:
Post a Comment