Skip to content

Instantly share code, notes, and snippets.

@bananaumai
Created June 11, 2013 12:37
Show Gist options
  • Save bananaumai/5756479 to your computer and use it in GitHub Desktop.
Save bananaumai/5756479 to your computer and use it in GitHub Desktop.
演算子オーバーロードとドメインオブジェクト ref: http://qiita.com/items/bf42e8accc7550ba3943
object Caluculator extends App {
val walet:List[Money] = Money(100) :: Money(200) :: Money(300) :: Nil
val sum:Money = (Money(0) /: walet) (_ + _)
println(sum.toString)
}
case class Money(private val value: BigDecimal) {
def +(that: Money): Money = new Money(this.value + that.value)
def -(that: Money): Money = new Money(this.value - that.value)
def >(that: Money): Boolean = this.value > that.value
def >=(that: Money): Boolean = this.value >= that.value
def <(that: Money): Boolean = this.value < that.value
def <=(that: Money): Boolean = this.value <= that.value
override def toString = this.value.toString
}
import org.specs2.mutable._
class MoneySpec extends Specification {
"Money" should {
"Moneyの加算" in {
Money(100) + Money(200) must_== Money(300)
}
"Moneyの減算" >> {
Money(200) - Money(100) must_== Money(100)
}
"Moneyの比較" >> {
"==" in {
val a = Money(100)
val b = Money(100)
val c = Money(100)
a == b must_== true
b == a must_== true
b == c must_== true
a == c must_== true
a == Money(101) must_== false
}
">" in {
Money(100) > Money(99) must_== true
Money(100) > Money(100) must_== false
}
">=" in {
Money(100) >= Money(99) must_== true
Money(100) >= Money(100) must_== true
Money(100) >= Money(101) must_== false
}
"<" in {
Money(100) < Money(100) must_== false
Money(100) < Money(101)
}
">=" in {
Money(100) <= Money(101) must_== true
Money(100) <= Money(100) must_== true
Money(100) <= Money(99) must_== false
}
}
"Moneyを文字列に変換する" in {
val Money100 = Money(100)
Money100.toString must_== "100"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment