Search code examples
scalaencapsulation

Setting format of setters & getters in Scala case classes


In Scala, I have a case class:

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
}

When I have an instance of the case class, I have to use

myMonthSelectionInfo.monthSelection

and

myMonthSelectionInfo.eq(newMonthSelection)

to get & set the MonthSelection instance contained within.

Is there any nice Scala way to format the getter & setter to look more like regular Java POJOs? e.g.

myMonthSelectionInfo.setMonthSelection(newMonthSelection)

Solution

  • There is @BeanProperty annotation to generate getters and setters for fields.

    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