1

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インスタンスを取得および設定します。

ゲッターとセッターを通常のJavaPOJOのようにフォーマットするためのScalaの優れた方法はありますか?例えば

myMonthSelectionInfo.setMonthSelection(newMonthSelection)
4

2 に答える 2

6

@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
于 2012-05-02T10:58:55.340 に答える
0

オブジェクト指向プログラミングでは、ゲッターとセッターは、現実世界でいくつかの利点があることにほとんどの人が同意するものです。残念ながら、彼らは時々書くのが面倒になることがあります。それらは通常多くのコードで構成されていませんが、同じものを何度も何度も書くと、非常に速く古くなります。私の経験では、ほとんどのゲッターとセッターは非常に似ているので、同じ結果を達成するための「より良い」方法がなければならないのは当然です。

このリンクはあなたを助けるかもしれません。

于 2012-05-02T10:58:28.770 に答える