We need a final improvement now. The version of the element that is shown in code 10.11 is not complete because he does not allow customers to stack elements of different widths together or to put elements of different heights together. For example, the following expression will not work correctly because the second row of the combined element is longer than the first line:
New Arrayelement (Array ("Hello")) above
new Arrayelement (Array ("world!")
Similarly, the following expression does not work properly, because the first arrayelement height is two, and the second height is only one:
New Arrayelement (Array ("One", "two")) beside
new Arrayelement (Array ("one")
Code 10.13 shows a private help method, widen, that can take a width to make arguments and return the element of that width. The result contains the contents of the element, centered, left and right with the space required to get the desired width. Code 10.13 also shows a similar method, heighten, that performs the same function in a vertical direction. The widen method is called by the above to ensure that the element is stacked together with the same width. Similarly, the heighten method is called by beside to make sure that the elements that come together have the same height. With these changes, the layout library can be used.
Import Element.elem abstract class Element {def contents:array[string] def width:int = contents (0). Length de F height:int = Contents.length def above (that:element): Element = {val This1 = This widen that.width val that1 = t Hat widen this.width Elem (this1.contents + + that1.contents)} def beside (that:element): Element = {val This1 = thi S heighten that.height val that1 = that heighten this.height elem (for (line1, line2) <-this1.contents zip th at1.contents) yield line1 + line2)} def widen (w:int): Element = if (W < = width) This else {Val Left = Elem (", (w-width)/2, height) var right = Elem (", w–width-left.width, height) left beside this beside R ight} def heighten (h:int): Element = if (H < = height) This else {val top = Elem (', Width, (h-height) /2 var bot = Elem (', width, h–height-top.height) Top above this above bot} override def toString = Conten TS mkstring "\ n"}
Code 10.13 has the element of the widen and heighten methods