I am doing a training exercise in Scala and getting this val reassignment error. I don't see where I am reassigning a new value to a val
class personTest
{
val alf = Person("Alf", 30, List(EmailAddress("[email protected]")))
val fredrik = Person("Fredrik", 33, List(EmailAddress("[email protected]"), EmailAddress("[email protected]")))
val johannes = Person("Johannes", 0, Nil)
val persons = List(alf, fredrik, johannes)
@Test
def testNameToEmailAddress
{
// Create a map from each persons name to their e-mail addresses,
// filtering out persons without e-mail addresses
// Hint: First filter list, then use foldLeft to accumulate...
val emptyMap: Map[String, List[EmailAddress]] = Map()
val nameToEmail = persons.filter(_.emailAddresses.length>0).foldLeft(emptyMap)((b,p)=> b+=p.name->p.emailAddresses)
assertEquals(Map(alf.name -> alf.emailAddresses, fredrik.name -> fredrik.emailAddresses), nameToEmail)
}
}
and I am getting this error
error: reassignment to val
val nameToEmail = persons.filter(_.emailAddresses.length>0).foldLeft(emptyMap)((b,p)=> b+=p.name->p.emailAddresses)
b
which is the name of a parameter to your closure is itself a val
, which cannot be reassigned.
foldLeft
works by taking passing the return value of one invocation of the closure as the parameter b
to the next, so all you need to do is return b + (p.name->p.emailAddresses)
. (Don't forget the parentheses for precedence.)
You're reassigning val b
in the expression b+=p.name->p.emailAddresses
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With