1

I'd like to add a member to list but the list is immutable. I was told that Scala prefers immutable list in many perspective. Thanks in advance.

 class Family[T]{
    val list: List[T] = List();
    def add(member: T): Unit = { member :: this.list }
    def getFamilyNames(f: T => String){
        println(list.size)
        list.foreach {
            println
        }
    }
}
JJ80
  • 29
  • 2
  • 1
    It depends on which part you want to be immutable. If you want an immutable list, you can keep it inside a mutable variable, i.e. `var list = List.empty[T]`, and then *update the reference* to that list. – Yuval Itzchakov Jul 03 '17 at 08:14

3 Answers3

0

you can mutable List called ListBuffer[T] or ArrayBuffer[T]

class Family[T]{

  val list = ListBuffer[T]()

  def add(member: T): Unit = { this.list+=member }

  def getFamilyNames(f: T => String){

    println(list.size)
    list.foreach {
      println
    }
  }

}

class SomeSpecs extends FunSuite with Matchers {

  test("adds value to family") {

    val fam  = new Family[String]
    fam.add(new String("some value"))
    fam.add(new String("some other value"))

    fam.list shouldBe ListBuffer("some value", "some other value")
  }
}

Please read Which scala mutable list to use? for more info.

prayagupa
  • 30,204
  • 14
  • 155
  • 192
0

Your add method doesn't do what you're expecting. member :: this.list does return a new list with the extra member added to it. However, you're explicitly discarding it's return value which is of type List[T]. That is, prepending an element in a list doesn't modify the list in place: it just returns a new immutable List. What you likely want to have is something along the lines of:

var list: List[T] = List() // this must be a var to reassign to it
...
def add(member: T): Unit = { list = member :: this.list }

Usually, though, you want to avoid side effects, if you want to stick to a functional approach.

DeusEx
  • 147
  • 1
  • 7
0

If you want to have everything immutable than you should create new instance of Family because in other cases the instance of Family is mutable

class Family[T](list: List[T] = List()){
  def add(member: T): Unit = new Family(member :: this.list)
}

If Family is a Bulder of something than better to use a mutable collection. If it is not a builder, please review usage of it, may be you don't need the method 'add' at all.

Ivan
  • 462
  • 3
  • 13