Reputation: 4719
I was working on a code in which I declared a 'val' type variable and passed it to a recursive function which changes it:
def calculateDates(from: LocalDate, until: LocalDate, by: RDate, holidays: HolidayCalendar): Seq[LocalDate] =
{
val dateSeq: Seq[LocalDate] = Seq(from)
def calculateDatesRecur(from: LocalDate, dateSeq: Seq[LocalDate]): Seq[LocalDate] =
{
val date = by(from, holidays)
if (date.compareTo(until) <= 0)
calculateDatesRecur(date, dateSeq :+ date)
else
dateSeq
}
calculateDatesRecur(from, dateSeq)
}
'dateSeq' is a variable that ultimately is a list of dates from 'from' to 'until'. Well, it turns out it works. It shouldn't right? Because the 'dateSeq' variable has been initialised as 'val'. Is it that a copy of it is sent to the recursive function?
Upvotes: 0
Views: 120
Reputation: 15074
It isn't that a copy of dateSeq
is passed into calculateDatesRecur
, rather, the expression dateSeq :+ date
creates a new Seq[Date]
(with the newly added date, and without modifying the dateSeq
parameter), which is then passed to the recursive call. In this way, a final Seq[Date]
is built up from successive immutable, intermediate values, and eventually handed back when the else
clause is executed.
Upvotes: 2
Reputation: 12573
dateSeq :+ date
returns the new object. Check the definition of :+ method: http://www.scala-lang.org/api/current/index.html#scala.collection.Seq
Upvotes: 0