我构建了以下类:
class Player(val name: String, val onField: Boolean, val draft: Int, val perc: Int, val height: Int, val timePlayed: Int) {
override def toString: String = name
我正在努力
def play(team: List[Player]): List[Player] =
team map (p => new Player(p.name, p.onField, p.draft, p.perc, p.height, p.timePlayed + 1))
这实际上是将字段“timePlayed”递增 1,并返回新的玩家“列表”。
有没有更方便的方法呢?也许:
def play(team: List[Player]): List[Player] =
team map (p => p.timeIncremented())
我的问题是如何以更方便的方式实现 timeIncremented()?这样我就不必做:
new Player(p.name, p.onField, p.draft, p.perc, p.height, p.timePlayed + 1)
谢谢!
最佳答案
您可以将 Player 定义为 case class
并使用编译器生成的方法 copy
:
case class Player(name: String, onField: Boolean, draft: Int, perc: Int, height: Int, timePlayed: Int) {
override def toString: String = name
}
def play(team: List[Player]): List[Player] =
team map (p => p.copy(timePlayed = p.timePlayed + 1))
此外,如您所见,构造函数参数默认为 val
。
并且您可以在 Player
中定义 timeIncremented
并完全按照您的需要使用它:
case class Player(name: String, onField: Boolean, draft: Int, perc: Int, height: Int, timePlayed: Int) {
override def toString: String = name
def timeIncremented: Player = copy(timePlayed = this.timePlayed + 1)
}
def play(team: List[Player]): List[Player] =
team map (_.timeIncremented)
对于更复杂的情况,您可以查看镜头:
http://akisaarinen.fi/blog/2012/12/07/boilerplate-free-functional-lenses-for-scala/
Cleaner way to update nested structures
关于scala - 更新不可变对象(immutable对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20211022/