Reputation: 29
Can anyone explain in detail what this function is doing and what is the use of scala.collection.mutable.ListBuffer.empty[Int]
?
def f(num: Int, arr: List[Int]): List[Int] = {
val l = scala.collection.mutable.ListBuffer.empty[Int]
arr.foreach(i => {
println(i)
(1 to num).foreach(_ => l += i)
})
l.toList
}
Upvotes: 0
Views: 98
Reputation: 14825
ListBuffer.empty[Int]
is used for instantiating the ListBuffer
ListBuffer.empty[Int]
is same as ListBuffer[Int]()
ListBuffer
is mutable list.
i
of arr list.num
times i
is added to list bufferLater the mutable list is converted to immutable list using toList
call
That means
every value of
arr
list is added to list buffernum
times
# Scala REPL
scala> :paste
// Entering paste mode (ctrl-D to finish)
def f(num: Int, arr: List[Int]): List[Int] = {
val l = scala.collection.mutable.ListBuffer.empty[Int]
arr.foreach(i => {
println(i)
(1 to num).foreach(_ => l += i)
})
l.toList
}
// Exiting paste mode, now interpreting.
f: (num: Int, arr: List[Int])List[Int]
scala> f(10, (1 to 10).toList)
1
2
3
4
5
6
7
8
9
10
res2: List[Int] = List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10)
Upvotes: 1