我們還需要最后一個改進,之前的 Element 實現(xiàn)不夠完善,只支持同樣高度和同樣寬度的 Element 使用 above 和 beside 函數(shù),比如下面的代碼將無法正常工作,因為組合元素的第二行比第一行要長:
new ArrayElement(Array("hello")) above
new ArrayElement(Array("world!"))
與之相似的,下面的表達式也不能正常工作,因為第一個 ArrayElement 高度為二,而第二個的高度只是一
new ArrayElement(Array("one", "two")) beside
new ArrayElement(Array("one"))
下面代碼展示了一個私有幫助方法,widen,能夠帶個寬度做參數(shù)并返回那個寬度的 Element。結(jié)果包含了這個 Element 的內(nèi)容,居中,左側(cè)和右側(cè)留需帶的空格以獲得需要的寬度。這段代碼還展示了一個類似的方法,heighten,能在豎直方向執(zhí)行同樣的功能。widen 方法被 above 調(diào)用以確保 Element 堆疊在一起有同樣的寬度。類似的,heighten 方法被 beside 調(diào)用以確保靠在一起的元素具有同樣的高度。有了這些改變,布局庫函數(shù)可以使用了
abstract class Element {
def contents: Array[String]
def height: Int = contents.length
def width: Int = if (height == 0) 0 else contents(0).length
def above(that: Element) :Element =
Element.elem(this.contents ++ that.contents)
def beside(that: Element) :Element = {
Element.elem(
for(
(line1,line2) <- this.contents zip that.contents
) yield line1+line2
)
}
def widen(w: Int): Element =
if (w <= width) this
else {
val left = Element.elem(' ', (w - width) / 2, height)
var right = Element.elem(' ', w - width - left.width, height)
left beside this beside right
}
def heighten(h: Int): Element =
if (h <= height) this
else {
val top = Element.elem(' ', width, (h - height) / 2)
var bot = Element.elem(' ', width, h - height - top.height)
top above this above bot
}
override def toString = contents mkString "\n"\
}
更多建議: