Scala中變高變寬的實現(xiàn):heighten和widen
我們現(xiàn)在需要***一個改良。展示在代碼10.11中的Element的版本并不完全,因為他不允許客戶把不同寬度的元素堆疊在一起,或者不同高度的元素靠在一起。比方說,下面的表達式將不能正常工作,因為組合元素的第二行比***行要長:
與之相似的,下面的表達式也不能正常工作,因為***個ArrayElement高度為二,而第二個的高度只是一:
- new ArrayElement(Array("hello")) above
- new ArrayElement(Array("world!"))
- new ArrayElement(Array("one", "two")) beside
- new ArrayElement(Array("one"))
51CTO編輯推薦:Scala編程語言專題
代碼10.13展示了一個私有幫助方法,widen,能夠帶個寬度做參數(shù)并返回那個寬度的Element。結(jié)果包含了這個Element的內(nèi)容,居中,左側(cè)和右側(cè)留需帶的空格以獲得需要的寬度。代碼10.13還展示了一個類似的方法,heighten,能在豎直方向執(zhí)行同樣的功能。widen方法被above調(diào)用以確保Element堆疊在一起有同樣的寬度。類似的,heighten方法被beside調(diào)用以確??吭谝黄鸬脑鼐哂型瑯拥母叨?。有了這些改變,布局庫可以待用了。
- 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
【相關(guān)閱讀】