Scala中变高变宽的实现:heighten和widen

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

成都创新互联专业为企业提供威远网站建设、威远做网站、威远网站设计、威远网站制作等企业网站建设、网页设计与制作、威远企业网站模板建站服务,十载威远做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。

 
 
 
  1. new ArrayElement(Array("hello")) above  
  2. new ArrayElement(Array("world!"))  

与之相似的,下面的表达式也不能正常工作,因为***个ArrayElement高度为二,而第二个的高度只是一:

 
 
 
  1. new ArrayElement(Array("one", "two")) beside  
  2. new ArrayElement(Array("one"))  

编辑推荐:Scala编程语言专题

代码10.13展示了一个私有帮助方法,widen,能够带个宽度做参数并返回那个宽度的Element。结果包含了这个Element的内容,居中,左侧和右侧留需带的空格以获得需要的宽度。代码10.13还展示了一个类似的方法,heighten,能在竖直方向执行同样的功能。widen方法被above调用以确保Element堆叠在一起有同样的宽度。类似的,heighten方法被beside调用以确保靠在一起的元素具有同样的高度。有了这些改变,布局库可以待用了。

 
 
 
  1. import Element.elem  
  2. abstract class Element {  
  3.  def contents: Array[String]  
  4.  def width: Int = contents(0).length  
  5.  def height: Int = contents.length  
  6.  def above(that: Element): Element = {  
  7.   val this1 = this widen that.width  
  8.   val that1 = that widen this.width  
  9.   elem(this1.contents ++ that1.contents)  
  10.  }  
  11.  def beside(that: Element): Element = {  
  12.   val this1 = this heighten that.height  
  13.   val that1 = that heighten this.height  
  14.   elem(  
  15.    for ((line1, line2) < - this1.contents zip that1.contents)  
  16.    yield line1 + line2  
  17.   )  
  18.  }  
  19.  def widen(w: Int): Element =  
  20.   if (w < = width) this 
  21.   else {  
  22.    val left = elem(' ', (w - width) / 2, height)  
  23.    var right = elem(' ', w – width - left.width, height)  
  24.    left beside this beside right  
  25.   }  
  26.  def heighten(h: Int): Element =  
  27.   if (h < = height) this 
  28.   else {  
  29.    val top = elem(' ', width, (h - height) / 2)  
  30.    var bot = elem(' ', width, h – height - top.height)  
  31.    top above this above bot  
  32.  }  
  33.  override def toString = contents mkString "\n" 
  34. }  

代码 10.13 有了widen和heighten方法的Element

【相关阅读】

  1. 学习Scala的定义工厂对象
  2. 如何实现Scala的above,beside和toString
  3. Scala学习:使用组合与继承
  4. 在Scala中定义final成员
  5. Scala程序中如何实现多态和动态绑定

网站栏目:Scala中变高变宽的实现:heighten和widen
转载源于:http://www.shufengxianlan.com/qtweb/news22/122622.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联