Now, one is able to write the code:
val x = new {
val r = 0
}
The code will be compiled without errors, but the type of x will be just “Object”. It seems strange, because we have all the information about the class, except its name. So, the type must be
AnyRef {val r: Int}
or, maybe, some type, whose name are generated. Intellij Idea, by the way, now says, that the type is
Object {val r: Int}
but Scala compiler doesn’t think so, and you cannot call x.r in the next line.
This way, the construction is rather useless, because nothing useful can be done with a plain Object.
On the other hand, if the real type was derived, we would do nice things, such as
collection.view
.map { x =>
new {
val value = x
val result = veryLongComputation(x)
}
}
.filter(_.result > 0.5)
.foreach(x => println(s"result(${x.value}) = ${x.result}"))
Of course, in this simple case, one may use just a Tuple2, but its fields have no sensible names, and, all in all, you are able to do much more with a class than with a Tuple.
Inside “map” compiler knows all about the anonymous class. Its type should be
AnyRef {val value: Int; val result: Int}
So, the type of the result of “map” calling should be
CollectionViewType[ AnyRef { val value: Int; val result: Int } ]
So, the type of the argument of the “filter” should be
AnyRef { val value: Int; val result: Int }
etc.
And here is no boilerplate code, as if we would need to define the temporary class before the collection call-chain.