Reputation: 159754
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)
Upvotes: 1
Views: 2876
Reputation: 3066
We can use @BeanProperty
in scala 2.11.
import scala.beans.BeanProperty
case class Employee(@BeanProperty var id: Long, @BeanProperty var name: String, @BeanProperty var age: Long)
Upvotes: 0
Reputation: 10776
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
Upvotes: 6
Reputation: 4543
In object oriented programming, getters and setters are something that most would agree have some real world benefits. Unfortunately, they can sometimes be annoying to write. They usually do not consist of a lot of code , but when you have the write the same thing over and over and over it gets old really fast. In my experience, most getters and setters are very much alike so it stands to reason that there must be a “better” way to accomplish the same result.
This link may help you.
Upvotes: 0