5.9. Supporting a Fluent Style of Programming

Problem

You want to create an API so developers can write code in a fluent programming style, also known as method chaining.

Solution

A fluent style of programming lets users of your API write code by chaining method calls together, as in this example:

person.setFirstName("Leonard")
      .setLastName("Nimoy")
      .setAge(82)
      .setCity("Los Angeles")
      .setState("California")

To support this style of programming:

  • If your class can be extended, specify this.type as the return type of fluent style methods.

  • If you’re sure that your class won’t be extended, you can optionally return this from your fluent style methods.

The following code demonstrates how to specify this.type as the return type of the set* methods:

class Person {

  protected var fname = ""
  protected var lname = ""

  def setFirstName(firstName: String): this.type = {
    fname = firstName
    this
  }

  def setLastName(lastName: String): this.type = {
    lname = lastName
    this
  }

}

class Employee extends Person {

  protected var role = ""

  def setRole(role: String): this.type = {
    this.role = role
    this
  }
  override def toString = {
    "%s, %s, %s".format(fname, lname, role)
  }

}

The following test object demonstrates how these methods can be chained together:

object Main extends App {

  val employee = new Employee

  // use the fluent methods
  employee.setFirstName("Al")
          .setLastName("Alexander")
          .setRole("Developer")
  println(employee)

}

Discussion

If you’re sure your class won’t be extended, specifying this.type as the return type of ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.