Open In App

Heighten and Widen In Scala

Improve
Improve
Like Article
Like
Save
Share
Report


Heighten and Widen are the functions needed to enable the clients to place elements of different widths on top of each other, or place elements of different heights beside each other. These functions takes a width or a height and returns an element having the same width or height respectively.

For example, evaluating the following expression would not work correctly, because the second line in the combined element is longer than the first:

new ArrayElement(Array("geeks")) above 
new ArrayElement(Array("forgeeks"))

Similarly, evaluating the following expression would not work properly too, because the first ArrayElement has a height of two, and the second a height of only one:

new ArrayElement(Array("yes", "no")) beside 
new ArrayElement(Array("yes"))

The code fragment below contains a private function widen, which takes a width and returns an Element of that width. The result contains the contents of this Element centered padded to the left and right by any spaces needed to achieve the required width. Similarly, it contains another private function heighten, which performs the same function in the vertical direction. The widen method is invoked by above to ensure that Elements placed above each other have the same width. Similarly, the heighten method is invoked by beside to ensure that elements placed beside each other have the same height.

Example:




// Widen function
def widen(w: Int): Element =
  
// if w is less than or equal to the width of the Element
// then do nothing
if (w <= width) this 
else{
  
    // if w is greater than the width of the Element
    // then add padding of spaces
  
    // half padding on the left
    val left = elem(' ', (w - width) / 2, height)
  
    // half padding on the right
    var right = elem(' ', w - width - left.width, height)
  
    left beside this beside right
}
  
// Heighten function
def heighten(h: Int): Element =
  
// if h is less than or equal to the height of the Element
// then do nothing
if (h <= height) this 
else{
  
    // if h is greater than the height of the Element
    // then add padding of spaces
  
    // half padding on the top
    val top = elem(' ', width, (h - height) / 2)
  
    // half padding at the bottom
    var bot = elem(' ', width, h - height - top.height)
  
    top above this above bot
}




Last Updated : 04 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads