在Scala案例类中设置setter和getter的格式

Rei*_*eus 1 encapsulation 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
}
Run Code Online (Sandbox Code Playgroud)

当我有一个案例类的实例时,我必须使用

myMonthSelectionInfo.monthSelection

myMonthSelectionInfo.eq(newMonthSelection)

获取和设置其中包含的MonthSelection实例.

是否有任何不错的Scala方法可以将getter和setter格式化为更像常规Java POJO?例如

myMonthSelectionInfo.setMonthSelection(newMonthSelection)
Run Code Online (Sandbox Code Playgroud)

4e6*_*4e6 6

有一个@BeanProperty注释可以为字段生成getter和setter.

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
Run Code Online (Sandbox Code Playgroud)