Sunday, 28 September 2014

Starting with Scala

Scala is the new buzz word. I call it "a better Java". It is clean and rich with syntax sugars. Following is a program to manage money objects, to do operations on it and to convert from one currency to another.

Money.scala
class Money(val amount: Double = 0, val currency: String = Money.US$.currency, val valuePerUSD: Double = Money.US$.valuePerUSD) {

  def +(that: Money) = new Money((this.amount / this.valuePerUSD + that.amount / that.valuePerUSD) * this.valuePerUSD, this.currency, this.valuePerUSD)
  def -(that: Money) = new Money((this.amount / this.valuePerUSD - that.amount / that.valuePerUSD) * this.valuePerUSD, this.currency, this.valuePerUSD)
  def ->(that: Money) = new Money((this.amount / this.valuePerUSD) * (that.valuePerUSD), that.currency, that.valuePerUSD)

  override def toString = s"$currency$amount"
}
object Money {
  lazy val INR = new Money(currency = "INR", valuePerUSD = 60)
  val US$ = new Money(currency = "$", valuePerUSD = 1)
  lazy val SR = new Money(currency = "SR", valuePerUSD = 4)
}

Main.scala
object Main {
  def main(args: Array[String]) = {
    println("** Welcome to Scala Money Manager **")

    val _120INR = new Money(120, Money.INR.currency, Money.INR.valuePerUSD)
    println("My Balance = " + _120INR)
    println("My Balance in USD = " + (_120INR -> Money.US$))

    //Different ways of creating Money objects
    val _0Dollars = new Money
    val _10Dollars = new Money(10)
    val _0INR = new Money(currency = Money.INR.currency, valuePerUSD = Money.INR.valuePerUSD)

    println("Adding $10 to my balance, therefore My Balance = " + (_120INR + _10Dollars))
    println("Adding $12 and $8, converting result into INR = " + ((new Money(12) + new Money(8)) -> Money.INR))
    println("INR12 + SR10 = " + (new Money(12, Money.INR.currency, Money.INR.valuePerUSD) + new Money(10, Money.SR.currency, Money.SR.valuePerUSD)))

    val _1SaudiRiyal = new Money(1, Money.SR.currency, Money.SR.valuePerUSD)
    println("SR1 + INR120 + $2 in INR = " + (_1SaudiRiyal + _120INR + new Money(2) -> Money.INR))
  }
}

Output
** Welcome to Scala Money Manager **
My Balance = INR120.0
My Balance in USD = $2.0
Adding $10 to my balance, therefore My Balance = INR720.0
Adding $12 and $8, converting result into INR = INR1200.0
INR12 + SR10 = INR162.0
SR1 + INR120 + $2 in INR = INR255.0

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.

Do you like this article?