Generic Classes and Compound Classes give an overview of one (unfortunately small) aspect of Scala’s support for generics.
Scala, like Java, has support for generics, or parameterized types. In the simplest case, it works more or less like Java, with a slightly different syntax (and a more concise means of use, thanks to Scala’s type inference).
Suppose you wish to create a configuration system that maps keys to values, but that you want the values to be typed.
Symbols in Scala are fixed values created via a single quote. This is essentially the same concept as a
:symbol in Ruby)
This is pretty much what you’d get from Java, however it’s important to note that each of the four values we created are all typed, and each call to
.value returns a typed object that can be checked at runtime. If you were to try:
you would get a compile error.
Also note that, like in Java, if a class
Child extends a class
Configuration[Child] is not a subclass of
Configuration[Parent] (although you can change this behavior ).
Methods can also be genericized, as they can be in Java:
def doit[T](thing: T):String = thing.toString
Since Scala allows for multiple inheritance, the question arises: how do you specify that a type conform to multiple classes? If you wish to accept all
Entity classes that implement
Serializable, you can say
[Entity with Serializable].
My Thoughts on this Feature
This is where static typing really starts to take a turn for the confusing. While generics as described here are pretty straightforward, it opens a rabbit hole of potential confusion. That being said, this is really necessary to avoid gobs of casting and other nastiness that would be required otherwise. If I’m doing Java or Scala, I’d rather have it than not.