If you hard-code the type, like PartialFunction[Any,Nothing]
, you cannot restrict your function to take a more specific parameter than Any
.
By using a generic type parameter, you can end up with a more flexible satisfying all cases and especially making the function safe.
Let's assume you want a function aiming to take an Animal
as parameter and returning an Integer
.
Let's assume that function is declared as being:
def myFunction: PartialFunction[Any,Nothing]
Firstly, PartialFunction would not be specialized to Animal
at parameter side but to Any
. What about if I pass a Human
as parameter...., it would pass.. What about safety?
Secondly, If this function is declared as returning Nothing
, you can't return from it any value but Nothing
! Indeed, Nothing
subclasses all classes in Scala.
This leads to the known rule that return type parameter must always be covariant in order to make a function interesting, not the case with Nothing
.
In fact, Nothing
is interesting only when dealing with the empty
method of PartialFunction
. Logic since an empty PartialFunction
by definition involves nothing to return and should be forced to do it :)
You would ask: "So why don't we change the return type to Any
?"
Answer: Because you'd lose all the benefit of generic erasure time making compiler to add needed casts automatically => You wouldn't retrieve directly the Integer value, but Any. annoying..