2012-05-02 30 views
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实例包含在里面。

是否有任何不错的Scala方式来设置getter & setter,使其看起来更像普通的Java POJO?例如

myMonthSelectionInfo.setMonthSelection(newMonthSelection) 

回答

5

@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 
+0

请注意,这会产生额外的getter和setter。它不会删除Scala的默认获取者和设置者。 –

+0

完美,谢谢 – Reimeus

+0

不应该大小写不可改变? – Lukasz

0

在面向对象编程中,getters和setters是大多数人都会认同的东西,它具有一些真实世界的好处。不幸的是,他们有时会写作烦人。它们通常不包含很多代码,但是当你一遍又一遍地写同样的东西时,它会变得非常快速。根据我的经验,大多数getter和setter非常相似,所以有理由认为必须有一个“更好”的方法来达到同样的结果。

link可能会帮助你。