Sunday, October 25, 2015

Fluent API in Scala

Scala supports a fluent syntax for both method calls and class mixins, using traits and the with keyword. For example:

class Color { def rgb(): Tuple3[Decimal] }
object Black extends Color { override def rgb(): Tuple3[Decimal] = ("0", "0", "0"); }

trait GUIWindow {
   // Rendering methods that return this for fluent drawing
   def set_pen_color(color: Color): this.type
   def move_to(pos: Position): this.type
   def line_to(pos: Position, end_pos: Position): this.type

   def render(): this.type = this // Don't draw anything, just return this, for child implementations to use fluently

   def top_left(): Position
   def bottom_left(): Position
   def top_right(): Position
   def bottom_right(): Position
}

trait WindowBorder extends GUIWindow {
   def render(): GUIWindow = {
       super.render()
           .move_to(top_left())
           .set_pen_color(Black)
           .line_to(top_right())
           .line_to(bottom_right())
           .line_to(bottom_left())
           .line_to(top_left())
   }
}

class SwingWindow extends GUIWindow { ... }

val appWin = new SwingWindow() with WindowBorder
appWin.render()

Source

0 comments: