Lambda with Receiver

This feature defines helper functions indistinguishable from built-in language syntax. Such functions make it easy to create domain-specific languages (DSLs), covered later in Domain-Specific Languages.

The Kotlin standard library contains numerous useful helper functions. For example, StringBuilder is a modifiable object that builds a String. You can append String representations of different objects, and it returns an immutable String when you call toString():

// LambdaWithReceiver/StringBuilder.kt import atomictest.eq fun main(args: Array<String>) { val stringBuilder = StringBuilder() // [1] stringBuilder.append("Alphabet: ") // [2] for (ch in 'a'..'z') stringBuilder.append(ch) // [3] stringBuilder.toString() eq // [4] "Alphabet: abcdefghijklmnopqrstuvwxyz" }

append() automatically calls toString() on its argument and appends the result.

StringBuilder uses the Builder design pattern. When you want to build objects of a specific X type, the Builder pattern delegates the construction logic to an XBuilder class. This pattern works well when you can’t or don’t want to add modifying methods to X: when X is either immutable, or constructed once and allows only limited modifications.

StringBuilder.kt is simple, but somewhat verbose: we must repeat the name stringBuilder multiple times. Moreover, for each new case we also repeat the lines that create StringBuilder and produce the result (lines [1] and [4]), while what really differs in each case is what we append to stringBuilder (lines [2] and [3]).

End of sample. See for full early-access book.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.