Created
October 19, 2011 11:15
-
-
Save j5ik2o/1298006 to your computer and use it in GitHub Desktop.
Scala - コンパニオンオブジェクト
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
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