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.
Type-Constructor Polymorphism (a.k.a. higher-kinded types)
Without this feature you can, for example, express the idea of mapping a function over a list to return another list, or mapping a function over a tree to return another tree. But you can't express this idea generally without higher kinds.
With higher kinds, you can capture the idea of any type that's parameterised with another type. A type constructor that takes one parameter is said to be of kind
(*->*)
. For example,List
. A type constructor that returns another type constructor is said to be of kind(*->*->*)
. For example,Function1
. But in Scala, we have higher kinds, so we can have type constructors that are parameterised with other type constructors. So they're of kinds like((*->*)->*)
.For example:
Now, if you have a
Functor[List]
, you can map over lists. If you have aFunctor[Tree]
, you can map over trees. But more importantly, if you haveFunctor[A]
for any A of kind(*->*)
, you can map a function overA
.Manifests which are a sort of way at getting the type information at runtime, as if Scala had reified types.
Scala's equivalent of Java double brace initializer.
Scala allows you to create an anonymous subclass with the body of the class (the constructor) containing statements to initialize the instance of that class.
This pattern is very useful when building component-based user interfaces (for example Swing , Vaadin) as it allows to create UI components and declare their properties more concisely.
See http://spot.colorado.edu/~reids/papers/how-scala-experience-improved-our-java-development-reid-2011.pdf for more information.
Here is an example of creating a Vaadin button:
Maybe not too hidden, but I think this is useful:
This will automatically generate a getter and setter for the field that matches bean convention.
Further description at developerworks
Extractors which allow you to replace messy
if-elseif-else
style code with patterns. I know that these are not exactly hidden but I've been using Scala for a few months without really understanding the power of them. For (a long) example I can replace:With this, which is much clearer in my opinion
I have to do a bit of legwork in the background...
But the legwork is worth it for the fact that it separates a piece of business logic into a sensible place. I can implement my
Product.getCode
methods as follows..You can designate a call-by-name parameter (EDITED: this is different then a lazy parameter!) to a function and it will not be evaluated until used by the function (EDIT: in fact, it will be reevaluated every time it is used). See this faq for details