n.Ken n.Ken - 3 months ago 19
Scala Question

Add an element in listbuffer into a map (update a map)

I'm new to scala and I have a listbuffer in a map with this structure:

class Person(var name: String, var age: Int,note: ListBuffer[Note])
class Note(
email: String,
note: Int)

var m = Map[Tuple3[Int,Int,Int],Person]()


How can I update the map to add a new element into a listbuffer.

Answer

You should strongly consider using case classes in Scala - they give you a lot of good stuff for free. Assuming you do change your classes to case classes the following will achieve what you want:

import scala.collection.mutable.ListBuffer

case class Note(email: String, note:  Int)
case class Person(var name: String, var age: Int,note: ListBuffer[Note])


val n1 = Note("foo@gmail.com", 4)

val c1 = Person("John", 20, ListBuffer(n1))

val m = scala.collection.mutable.Map[(Int,Int,Int), Person]()

m += ((1,1,1) -> c1)

val n2 = Note("bar@gmail.com", 40)

m += ((1,1,1) -> c1.copy(note = c1.note += n2))

println(m)

res1: scala.collection.mutable.Map[(Int, Int, Int),Person] = Map((1,1,1) -> Person(John,20,ListBuffer(Note(foo@gmail.com,4), Note(bar@gmail.com,40))))