What are the hidden features of Scala that every Scala developer should be aware of?
One hidden feature per answer, please.
What are the hidden features of Scala that every Scala developer should be aware of?
One hidden feature per answer, please.
You can use
locally
to introduce a local block without causing semicolon inference issues.Usage:
locally
is defined in "Predef.scala" as:Being inline, it does not impose any additional overhead.
It's not exactly hidden, but certainly a under advertised feature: scalac -Xprint.
As a illustration of the use consider the following source:
Compiling this with scalac -Xprint:typer outputs:
Notice
scala.this.Predef.augmentString("xx").r
, which is a the application of theimplicit def augmentString
present in Predef.scala.scalac -Xprint:<phase> will print the syntax tree after some compiler phase. To see the available phases use scalac -Xshow-phases.
This is a great way to learn what is going on behind the scenes.
Try with
case class X(a:Int,b:String)
using the typer phase to really feel how useful it is.
Structural type definitions - i.e. a type described by what methods it supports. For example:
Notice that the type of the parameter
closeable
is not defined other than it has aclose
methodEarly Initialization:
Output:
Result types are dependent on implicit resolution. This can give you a form of multiple dispatch:
You can compose structural types with the 'with' keyword