2

I have the following class built:

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

}

I'm trying to do

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))

which is actually incrementing the field "timePlayed" by one, and return the new "List" of players.

Is there a more convenient way to do this? Perhaps:

def play(team: List[Player]): List[Player] =
team map (p => p.timeIncremented())

My question is how to implement timeIncremented() in a more convenient way? so that I don't have to do:

new Player(p.name, p.onField, p.draft, p.perc, p.height, p.timePlayed + 1)

Thanks!

1 Answer 1

7

You can use define Player as case class and use compiler generated method 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))

Also, as you see, constructor parameters are val by default.

And you can define timeIncremented in Player and use it exactly as you want:

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)

For more complex cases you can take a look at lenses:
http://akisaarinen.fi/blog/2012/12/07/boilerplate-free-functional-lenses-for-scala/
Cleaner way to update nested structures

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.