CHAINING OPERATOR ":"

Braden Steffaniak - Aug 12, 2022

INTRODUCING THE CHAINING OPERATOR ":"permalink

The "Chaining Operator" : // <=== this colon guy is a new idea in the realm of programming languages. It allows you to call a function on object x and override the return type of that function so that it returns the object reference for x.

But why?

Why is the chaining operator helpful? In some situations the return value of a function call is not needed, and in those cases it could be useful to call another function on that same object without re-referencing the value that invoked the function call. This can especially be useful for void functions. Where in traditional programming languages you would need to respecify the reference value again if you want to call another function call, with the chaining operator that is no longer necessary.

EXAMPLESpermalink

LOGGINGpermalink

Here is a one-liner that outputs three info messages:

log:info("one"):info("two"):info("three")

// or

log
  :info("one")
  :info("two")
  :info("three")

Without the chaining operator, the same would have to be achieved with a solution resembling this:

log.info("one")
log.info("two")
log.info("three")

NETWORKINGpermalink

Here is an example that demonstrates starting and closing a ServerSocket on a single line:

ServerSocket():start(8080):close()

Without the chaining operator, the same would have to be achieved with a solution resembling this:

let server = ServerSocket()
server.start(8080)
server.close()

STRING BUILDINGpermalink

A common use of the chaining operator is for string building:

let builder = StringBuilder()
  :append("this ")
  :append("is ")
  :append("an ")
  :append("example")

log.info(builder) // outputs: "this is an example"

or more concisely:

log.info(
  StringBuilder()
    :append("this ")
    :append("is ")
    :append("an ")
    :append("example")
) // outputs: "this is an example"

which are both functionally equivalent to:

let builder = StringBuilder()

builder.append("this ")
builder.append("is ")
builder.append("an ")
builder.append("example")

log.info(builder) // outputs: "this is an example"

LIST PROCESSINGpermalink

Call forEach multiple times on a List

let myInts = [1, 2, 3, 4]
var sum = 0

myInts
  .map({ _ * 2 })
  :forEach({ sum += _ })
  :forEach({ sum += 1 })
  :forEach({ sum += 3 })

expect(sum).toBe(36)
POSTS DOCUMENTATION