Section 16.6 Chapter 16 · Working with Lists 340
There are also variants of the mkString methods called addString which
append the constructed string to a StringBuilder object,
5
rather than re-
turning them as a result:
scala> val buf = new StringBuilder
buf: StringBuilder =
scala> abcde addString (buf, "(", ";", ")")
res21: StringBuilder = (a;b;c;d;e)
The mkString and addString methods are inherited from List’s super trait
Iterable, so they are applicable to all sorts of iterable collections.
Converting lists: elements, toArray, copyToArray
To convert data between the flat world of arrays and the recursive world of
lists, you can use method toArray in class List and toList in class Array:
scala> val arr = abcde.toArray
arr: Array[Char] = Array(a, b, c, d, e)
scala> arr.toString
res22: String = Array(a, b, c, d, e)
scala> arr.toList
res23: List[Char] = List(a, b, c, d, e)
There’s also a method copyToArray, which copies list elements to succes-
sive array positions within some destination array. The operation:
xs copyToArray (arr, start)
copies all elements of the list xs to the array arr, beginning with position
start. You must ensure that the destination array arr is large enough to
hold the list in full. Here’s an example:
scala> val arr2 = new Array[Int](10)
arr2: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
scala> List(1, 2, 3) copyToArray (arr2, 3)
scala> arr2.toString
res25: String = Array(0, 0, 0, 1, 2, 3, 0, 0, 0, 0)
5
This is class scala.StringBuilder, not java.lang.StringBuilder.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index