Created
June 11, 2013 12:37
-
-
Save bananaumai/5756479 to your computer and use it in GitHub Desktop.
演算子オーバーロードとドメインオブジェクト ref: http://qiita.com/items/bf42e8accc7550ba3943
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
object Caluculator extends App { | |
val walet:List[Money] = Money(100) :: Money(200) :: Money(300) :: Nil | |
val sum:Money = (Money(0) /: walet) (_ + _) | |
println(sum.toString) | |
} |
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
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 | |
} |
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
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