gpt4 book ai didi

scala - 重新分配给 Scala 中的 val

转载 作者:行者123 更新时间:2023-12-04 05:43:42 25 4
gpt4 key购买 nike

我正在 Scala 中进行培训练习并收到此 val 重新分配错误。我看不到在哪里将新值重新分配给 val

class personTest
{
val alf = Person("Alf", 30, List(EmailAddress("alf.kristian@gmail.com")))
val fredrik = Person("Fredrik", 33, List(EmailAddress("fredrik@vraalsen.no"), EmailAddress("fvr@knowit.no")))
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)
}

}

我收到这个错误
error: reassignment to val
val nameToEmail = persons.filter(_.emailAddresses.length>0).foldLeft(emptyMap)((b,p)=> b+=p.name->p.emailAddresses)

最佳答案

b这是闭包参数的名称本身就是 val ,不能重新分配。
foldLeft通过将一次闭包调用的返回值作为参数传递来工作 b到下一个,所以你需要做的就是返回 b + (p.name->p.emailAddresses) . (不要忘记括号的优先级。)

关于scala - 重新分配给 Scala 中的 val,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3908806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com