简体   繁体   中英

Functional data structures and data sharing. How does it work in Scala?

Say I have a method like the following (curried for better type inference)

def dropWhile[A](l: List[A]) (f: A => Boolean): List[A] = {

  l match {
    case h::t if f(h) => dropWhile(t)(f)
    case _ => l
  }
}

and then I call it as follows

scala> val lst = (1 to 10).toList
lst: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> dropWhile(lst) ( _ <= 4)
res0: List[Int] = List(5, 6, 7, 8, 9, 10)

and get the expected result back. My question is

lst is a list with its own memory address. By default, method arguments are passed by value so in

dropWhile(lst) ( _ <= 4)

lst will be copied over to method parameter l? and so the method will have its own copy in l and what is more, each recursive invocation should have its own copy? In that context, how does data sharing work?

lst will be copied over to method parameter l?

No, only the reference to the list will be copied as lst is passed in to dropWhile , not the elements of the list. The effect is both lst and l will each have a copy of the reference that points to the same object in memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM