Reputation: 3710
I'm attempting to do a method of an object x times, as per the contents of, say:
val obstacles = Vector[Obstacle](list...)
What I'm doing currently is just suffixing all out (where location
s are of type, say Location
):
val background: Pic = rectangle
background.place(obstacle1.shape, obstacle1.location)
.place(obstacle2.shape, obstacle2.location)
.place(shape3Pic, new Location(location3))
.place(shape4Pic, new Location(location4))...
..which I tried to do with map
:
obstacles.map(o => background.place(o.shape, o.location))
..however this then of course only returns a Vector[Obstacle]
, not the original background: Pic
with the "additions", and will not work with the shape3Pic: Pic
and shape4Pic: Pic
, as they are not Obstacle
.
Apparently this can be done in recursion?
Upvotes: 0
Views: 65
Reputation: 5325
You could also do it without recursion using foldLeft
shapes.foldLeft(background)((r,c) => r.place(c))
Or even shorter
shapes.foldLeft(background)(_ place _)
Upvotes: 3
Reputation: 3216
Assuming Background.place takes only Shape object, it could be as follows:
trait Shape { }
trait Background {
def place(shape: Shape): Background
}
@tailrec
def placeRecursive(shapes: Vector[Shape], background: Background): Background = {
shapes match {
case shape +: rest =>
placeRecursive(rest, background.place(shape))
case _ =>
background
}
}
Upvotes: 1