I'm learning Scala from the book "Scala for the Impatient". One section in the book illustrates the "fluent" style of programming with the following code snippet:
object Title
class Document {
private var useNextArgAs: Any = null
def set(obj: Title.type): this.type = { useNextArgAs = obj; this }
def to(arg: String) = if (useNextArgAs == Title) title = arg; else ...
}
The author then makes the following method call:
book set Title to "Scala for the Impatient"
Some questions here:
- Why is
useNextArgAstypeAny? The only type that's used in the example foruseNextArgAsis aTitle. Can you show a use case for usingAnyinstead ofTitle? - Method
setreturnsthisbut the return type isthis.type, notDocument? Isn'tthissupposed to be the instance? - In method
to,title = argrefers to non-existent vartitle? Where did it come from?
A possible (not entirely correct) implementation for this excercise from the book can be found (Spoiler Alert!) in github
The chapter 18 where this example comes from is labeled as "Senior Lib Designer" difficulty level. At this level a person should be well aware of re-use and extensibility issues, and consequences of mutable state in scala. This is definetely not a technic for beginners.
To OP's questions:
1) Why is useNextArgAs type Any? --- to make it support arbitrary attribute types in Document sub-classes.
Documentis not declaredfinal2) Method set returns this but the return type is this.type --- see Alvin Alexander's article below (you probably have the explanation in "Scala for the Impatient")
consider the following extension and play around with
set()andto()return type and value3) non-existent var title --- it is a mutable field in Document, just missing in the code snippet provided
Some extra reading on the subject: