Skip to content

Instantly share code, notes, and snippets.

@j5ik2o j5ik2o/gist:1298006
Created Oct 19, 2011

Embed
What would you like to do?
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
You can’t perform that action at this time.