我们现在需要***一个改良。展示在代码10.11中的Element的版本并不完全,因为他不允许客户把不同宽度的元素堆叠在一起,或者不同高度的元素靠在一起。比方说,下面的表达式将不能正常工作,因为组合元素的第二行比***行要长:

成都创新互联专业为企业提供威远网站建设、威远做网站、威远网站设计、威远网站制作等企业网站建设、网页设计与制作、威远企业网站模板建站服务,十载威远做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
- new ArrayElement(Array("hello")) above
 - new ArrayElement(Array("world!"))
 
与之相似的,下面的表达式也不能正常工作,因为***个ArrayElement高度为二,而第二个的高度只是一:
- new ArrayElement(Array("one", "two")) beside
 - new ArrayElement(Array("one"))
 
编辑推荐:Scala编程语言专题
代码10.13展示了一个私有帮助方法,widen,能够带个宽度做参数并返回那个宽度的Element。结果包含了这个Element的内容,居中,左侧和右侧留需带的空格以获得需要的宽度。代码10.13还展示了一个类似的方法,heighten,能在竖直方向执行同样的功能。widen方法被above调用以确保Element堆叠在一起有同样的宽度。类似的,heighten方法被beside调用以确保靠在一起的元素具有同样的高度。有了这些改变,布局库可以待用了。
- import Element.elem
 - abstract class Element {
 - def contents: Array[String]
 - def width: Int = contents(0).length
 - def height: Int = contents.length
 - def above(that: Element): Element = {
 - val this1 = this widen that.width
 - val that1 = that widen this.width
 - elem(this1.contents ++ that1.contents)
 - }
 - def beside(that: Element): Element = {
 - val this1 = this heighten that.height
 - val that1 = that heighten this.height
 - elem(
 - for ((line1, line2) < - this1.contents zip that1.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 right
 - }
 - 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 = contents mkString "\n"
 - }
 
代码 10.13 有了widen和heighten方法的Element
【相关阅读】