2012-05-02 23 views
1

にセッター&ゲッターの書式を設定すると、私はケースクラスを持っている:私はケースクラスのインスタンスを持っている場合はScalaでScalaのケースクラス

case class MonthSelectionInfo(monthSelection: MonthSelection.Value, customMonth:Int = 0, customYear:Int = 0) { 

def this(monthSelection: MonthSelection.Value) = { 
    this(monthSelection, 0, 0) 
} 
} 


object MonthSelection extends Enumeration { 
    type MonthSelection = Value 

    val LastMonth, ThisMonth, NextMonth, CustomMonth = Value 
} 

は、私が

myMonthSelectionInfo.monthSelectionを使用する必要があります

myMonthSelectionInfo.eq(newMonthSelection)

に&を入力すると、その中に含まれるMonthSelectionインスタンスが設定されます。

Getter & setterを通常のJava POJOのように見せかける便利なScalaの方法はありますか?例えば

myMonthSelectionInfo.setMonthSelection(newMonthSelection) 

答えて

5

@BeanPropertyアノテーションは、フィールドのゲッターとセッターを生成するためのものです。

case class MonthSelectionInfo(@reflect.BeanProperty var monthSelection: MonthSelection.Value) 

scala> val ms = MonthSelectionInfo(MonthSelection.LastMonth) 
ms: MonthSelectionInfo = MonthSelectionInfo(LastMonth) 

scala> ms.setMonthSelection(MonthSelection.ThisMonth) 

sscala> ms.getMonthSelection 
res4: MonthSelection.Value = ThisMonth 
+0

これは追加のゲッタとセッタを生成することに注意してください。 Scalaのデフォルトgetterとsetterは削除されません。 –

+0

パーフェクト、ありがとう – Reimeus

+0

クラスが不変であるべきではないでしょうか? – Lukasz

0

オブジェクト指向プログラミングでは、ゲッターとセッターはほとんどの場合、いくつかの現実的な利点があります。残念なことに、彼らは時には書くのが面倒かもしれません。彼らは通常、多くのコードで構成されていませんが、同じことを何度も何度も繰り返し書くと、本当に速くなっていきます。私の経験では、ほとんどのゲッターとセッターは非常に似ていますので、同じ結果を達成するには「より良い」方法が必要であるという理由があります。

このlinkがお手伝いできます。