Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassignment to a val in Scala

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)
like image 724
Mansur Ashraf Avatar asked Oct 11 '10 18:10

Mansur Ashraf


2 Answers

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

like image 113
Ken Bloom Avatar answered Sep 22 '22 12:09

Ken Bloom


You're reassigning val b in the expression b+=p.name->p.emailAddresses.

like image 23
Aaron Novstrup Avatar answered Sep 21 '22 12:09

Aaron Novstrup