Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
S ECTION 10.13 ยท Defining a factory object be described in detail in Chapter 15. For now, you can just think of this as a way to define two val s, line1 and line2 , for each step of the iteration. The for expression has a yield part and therefore yields a result. The result is of the same kind as the expression iterated over, i.e., it is an array. Each element of the array is the result of concatenating the corresponding lines, line1 and line2 . So the end result of this code is the same as in the first version of beside , but because it avoids explicit array indexing, the result is obtained in a less error-prone way. You still need a way to display elements. As usual, this is done by defin- ing a toString method that returns an element formatted as a string. Here is its definition: override def toString = contents mkString "\n" The implementation of toString makes use of mkString , which is defined for all sequences, including arrays. As you saw in Section 7.8, an expression like " arr mkString sep " returns a string consisting of all elements of the ar- ray arr . Each element is mapped to a string by calling its toString method. A separator string sep is inserted between consecutive element strings. So the expression, " contents mkString "\n" " formats the contents array as a string, where each array element appears on a line by itself. Note that toString does not carry an empty parameter list. This follows the recommendations for the uniform access principle, because toString is a pure method that does not take any parameters. With the addition of these three methods, class Element now looks as shown in Listing 10.9. 10.13 Defining a factory object You now have a hierarchy of classes for layout elements. This hierarchy could be presented to your clients "as is." But you might also choose to hide the hierarchy behind a factory object. A factory object contains methods that construct other objects. Clients would then use these factory methods for object construction rather than constructing the objects directly with new . An advantage of this approach is that object creation can be centralized and the details of how objects are represented with classes can be hidden. This hiding will both make your library simpler for clients to understand, because 201