Skip to content

Instantly share code, notes, and snippets.

@j5ik2o
Created October 19, 2011 11:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j5ik2o/1298006 to your computer and use it in GitHub Desktop.
Save j5ik2o/1298006 to your computer and use it in GitHub Desktop.
Scala - コンパニオンオブジェクト
package money
import java.util.Currency
import java.util.Locale
class Money(private val amount:BigDecimal, val currency: Currency){
def this(amount:BigDecimal) = this(amount, DEFAULT) // オブジェクトの定数が参照できる
def plus(other:Money) = { /*略*/ }
}
// クラスと同名のオブジェクトを定義できます。
// staticの変わりとして使える
object Money{
val USD = Currency.getInstance("USD")
val JPY = Currency.getInstance("JPY")
val DEFAULT = USD
def sum(moneies:List[Money]) = {
var result = BigDecimal(0)
for(money <- moneies){
result += money.amount // privateフィールドにアクセスできる
}
new Money(result)
}
// staticのような定数アクセス
println(Money.USD)
println(Money.JPY)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment