Chapter 10. Advanced Typing

By this point in the book you should have a pretty good understanding of the Scala language. If you have read the chapters and pursued the exercises, then you are already pretty good at defining classes, writing functions, and working with collections. You know everything you need to in order to go out and start building your own Scala applications.

However, if you want to be able to read other developers’ Scala code, read and understand the Scala API, or understand how Scala works, you will want to read this chapter. In it we will cover many of the type features that make the language possible.

One interesting feature is how the apparently high-level tuples and function literals are built with regular classes. Their fancy syntax belies their humble foundation, which you can validate by creating them as class instances:

scala> val t1: (Int, Char) = (1, 'a')
t1: (Int, Char) = (1,a)

scala> val t2: (Int, Char) = Tuple2[Int, Char](1, 'a')
t2: (Int, Char) = (1,a)

scala> val f1: Int=>Int = _ + 2
f1: Int => Int = <function1>

scala> val f2: Int=>Int = new Function1[Int, Int] { def apply(x: Int) = x * 2 }
f2: Int => Int = <function1>

Another interesting type feature is implicit classes. Implicit classes provide a type-safe way to “monkey-patch” new methods and fields onto existing classes. Through automatic conversion from the original class to the new class, methods and fields in the implicit class can be invoked directly on the original class without any ...

Get Learning Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.