2

我建立了以下课程:

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”加一,并返回新的玩家“列表”。

有没有更方便的方法来做到这一点?也许:

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)

谢谢!

4

1 回答 1

7

您可以使用将 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默认的。

timeIncremented您可以根据需要定义Player和使用它:

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/ 更新嵌套结构的更清洁方法

于 2013-11-26T07:45:31.283 回答